[hackerrank] Prepare > SQL > Advanced Select > Binary Tree Nodes
[문제]
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:
[MYSQL]
[ORCALE]
1 2
2 4
3 2
4 15
5 6
6 4
7 6
8 9
9 11
10 9
11 15
12 13
13 11
14 13
15 NULL
풀었던 문제인데.. 기억이 안나서 다시 찾아봤다.
검색어 : 오라클 계층형 쿼리
select N, P
,decode( P , NULL,'Root')
from BST
start with P is null
CONNECT BY PRIOR N = P
order by N;
-> root는 찾았고.. 이제 P에 대해 조건을 걸어야 하는데..
보기에 P칼럼에 N칼럼의 값이 없으면 leaf같음..
select N
,case
when P is null then 'Root'
when CONNECT_BY_ISLEAF = 0 then 'Inner'
when CONNECT_BY_ISLEAF = 1 then 'Leaf'
end
from BST
start with P is null
CONNECT BY PRIOR N = P
order by N;
https://devjhs.tistory.com/171
- 역할
계층형 쿼리에서 해당하는 로우가 자식노드가 있는지 없는지 여부를 체크
자식노드가 있을 경우 0 , 자식노드가 없을 경우 1
출처: https://devjhs.tistory.com/171 [키보드와 하루:티스토리]
'HackerRank > SQL' 카테고리의 다른 글
[hackerrank] Revising Aggregations - The Count Function (0) | 2022.08.22 |
---|---|
[hackerrank] New Companies (0) | 2022.08.22 |
[hackerrank] The PADS (0) | 2022.08.17 |
[hackerrank] type of triangle (0) | 2022.08.17 |
[hackerrank] Binary Tree Nodes (0) | 2022.08.09 |