코딩테스트/리트코드 SQL
[리트코드/SQL] 13. Tree node (608)
Sooyoon Jeong
2022. 12. 16. 01:05
🤔 문제 분석
1) Write an SQL query to report the type of each node in the tree.
Each node in the tree can be one of three types:
- "Leaf": if the node is a leaf node.
- "Root": if the node is the root of the tree.
- "Inner": If the node is neither a leaf node nor a root node.
Write an SQL query to report the type of each node in the tree.
2) Return the result table in any order.


💡 풀이
SELECT
distinct t1.id,
CASE
WHEN t1.p_id IS NULL THEN "Root"
WHEN t2.id IS NOT NULL THEN "Inner"
ELSE "Leaf"
END AS "type"
FROM Tree AS t1
LEFT JOIN Tree AS t2 ON t1.id = t2.p_id