[HackerRank MySQL] Binary Tree Nodes
2021. 2. 22. 22:13ㆍToday I Learned.../MySQL
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:
Solution
-- 1
select n, if(p is null, 'Root',
if(n in (select p from bst), 'Inner', 'Leaf'))
from bst
order by n
-- 2
select n, if(p is null, 'Root',
if(n not in (select p from bst where p is not null), 'Leaf', 'Inner'))
from bst
order by n
Reference: HackerRank Practice > SQL > Advanced Select > Binary Tree Nodes
'Today I Learned... > MySQL' 카테고리의 다른 글
[HackerRank MySQL Server] Challenges - 서브쿼리 WITH절 활용 (0) | 2021.02.24 |
---|---|
[HackerRank MySQL] The PADS (0) | 2021.02.23 |
[HackerRank MySQL] Placements (0) | 2021.02.22 |
[HackerRank MySQL] Weather Observation Station 19 - POWER & SQRT (SQL에서 제곱과 제곱근 계산하기) (0) | 2021.02.15 |
[HackerRank MySQL] Top Competitors (0) | 2021.02.15 |