1. 문제
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:
2. 답
SELECT DISTINCT bst.n
, CASE
WHEN bst.p IS NULL THEN "Root"
WHEN bst2.n IS NULL THEN "Leaf"
ELSE "Inner"
END
FROM bst
LEFT JOIN bst bst2 ON bst.n = bst2.p
ORDER BY bst.n
3. KEY POINT
- Leaf는 부모가 될 수 없고, Root는 부모가 없다는 성질을 이용
- CASE문을 이용해 조건에 따라 다른 출력을 할 수 있음
www.hackerrank.com/challenges/binary-search-tree-1/problem?h_r=internal-search
'MySQL > 문제풀이' 카테고리의 다른 글
[LeetCode] 서브쿼리 : 196. Delete Duplicate Emails (0) | 2021.03.25 |
---|---|
[LeetCode] UPDATE : 627. Swap Salary (0) | 2021.03.24 |
[HackerRank] Placements (0) | 2021.03.23 |
[HackerRank] Weather Observation Station 3 / Weather Observation Station 19 (0) | 2021.03.23 |
[HackerRank] Top Competitors (0) | 2021.03.23 |
댓글