출처 : LeetCode Tree Node
| Colume Name | Type |
|---|---|
| id | int |
| p_id | int |
id is the column with unique values for this table.
Each row of this table contains information about the id of a node and the id of its parent node in a tree.
The given structure is always a valid tree.
Each node in the tree can be one of three types:
Write a solution to report the type of each node in the tree.
Return the result table in any order.
The result format is in the following example.
Example 1

Sample Input 1
Tree table:
| id | p_id |
|---|---|
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
Sample Output 1
| id | p_id |
| 1 | Root |
| 2 | Inner |
| 3 | Leaf |
| 4 | Leaf |
| 5 | Leaf |
Sample Input 2
Tree table:
| id | p_id |
|---|---|
| 1 | null |
Sample Output 2
| id | p_id |
| 1 | Root |
1) 부모가 없으면 -> Root
2) 자식이 있으면 -> Inner
2) 부모는 있지만 자식이 없으면 -> Leaf
내 답안 📕
SELECT id
, CASE
WHEN p_id IS NULL THEN 'Root'
WHEN id IN (SELECT DISTINCT p_id FROM Tree) THEN 'Inner'
ELSE 'Leaf'
END AS type
FROM Tree;
p_id가 NULL이면 부모가 존재하지 않으니 Root
id가 다른 행들의 p_id에 존재한다면 자식이 있는것이므로 Inner
둘 다 아니면 자식이 없는 Leaf로!
출력
| id | p_id |
| -- | ------ |
| 1 | Root |
| 2 | Inner |
| 3 | Leaf |
| 4 | Leaf |
| 5 | Leaf |