Tree Node - LeetCode

Pepzera·2026년 1월 26일

SQL코딩테스트

목록 보기
3/18

Tree Node 문제

출처 : LeetCode Tree Node

Colume NameType
idint
p_idint

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:

  • "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 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:

idp_id
1null
21
31
42
52

Sample Output 1

| id |  p_id  |
|  1 |  Root  |
|  2 |  Inner |
|  3 |  Leaf  |
|  4 |  Leaf  |
|  5 |  Leaf  |

Sample Input 2
Tree table:

idp_id
1null

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  |

0개의 댓글