Binary Tree Nodes
Your Binary Tree Nodes submission got 30.00 points.
You are now 50 points away from the 1st star for your sql badge.
You are given a table, BST, containing two columns: N and P, where N represents the value of a node in Binary Tree, and P is the parent of N.
Write a query to find the node type of Binary Tree ordered by the value of the node. Output one of the following for each node:
- Root: If node is root node.
- Leaf: If node is leaf node.
- Inner: If node is neither root nor leaf node.
Sample Input
Sample Output
1 Leaf
2 Inner
3 Leaf
5 Root
6 Leaf
8 Inner
9 Leaf
Explanation
The Binary Tree below illustrates the sample:
- Orace //내장 함수
SELECT n
,CASE
WHEN CONNECT_BY_ISLEAF = 1 THEN 'Leaf'
WHEN LEVEL =1 THEN 'Root'
ELSE 'Inner' END
FROM BST
START WITH P IS NULL
CONNECT BY PRIOR N = P
ORDER BY N
;
- Best Simple
SELECT N,
CASE
WHEN P IS null THEN 'Root'
WHEN N IN (SELECT DISTINCT P FROM BST) THEN 'Inner'
ELSE 'Leaf'
END
FROM BST
ORDER BY N;
- NOT IN 의 함정
- null 일 때 함정이 있음.
Select N,
CASE WHEN x.N NOT IN (select distinct P from BST where P IS NOT NULL) THEN 'Leaf'
WHEN x.P IS NULL THEN 'Root'
ELSE 'Inner'
END AS NodeType
from BST x
order by N
- 개행 시점은 언제가 좋을까?
- SELECT
- FROM
- WHERE
- ORDER BY
- GROUP BY
- HAVING
반응형
'SW Programming > SQL' 카테고리의 다른 글
SQL문제 풀이 및 연습할 수 있는 사이트 (0) | 2019.09.19 |
---|
댓글