본문 바로가기

코딩테스트/SQL - Leetcode

608. Tree Node

Table: Tree

+-------------+------+
| Column 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:

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

Input: 
Tree table:
+----+------+
| id | p_id |
+----+------+
| 1  | null |
| 2  | 1    |
| 3  | 1    |
| 4  | 2    |
| 5  | 2    |
+----+------+
Output: 
+----+-------+
| id | type  |
+----+-------+
| 1  | Root  |
| 2  | Inner |
| 3  | Leaf  |
| 4  | Leaf  |
| 5  | Leaf  |
+----+-------+
Explanation: 
Node 1 is the root node because its parent node is null and it has child nodes 2 and 3.
Node 2 is an inner node because it has parent node 1 and child node 4 and 5.
Nodes 3, 4, and 5 are leaf nodes because they have parent nodes and they do not have child nodes.

Example 2:

Input: 
Tree table:
+----+------+
| id | p_id |
+----+------+
| 1  | null |
+----+------+
Output: 
+----+-------+
| id | type  |
+----+-------+
| 1  | Root  |
+----+-------+
Explanation: If there is only one node on the tree, you only need to output its root attributes.

 

-- 풀이
select distinct t1.id
     , if(t1.p_id is null, 'Root', if(t2.id is null, 'Leaf', 'Inner')) as type
  from Tree t1
  left join Tree t2
    on t1.id = t2.p_id;

 

if 구문을 활용한다.

처음 봤을 때는 어떻게 풀까 하다가 case when 구문을 사용했는데 너무 복잡해졌다.

if 구문을 쓰면 훨씬 간단하게 풀릴 문제였는데...

 

일단 어렵게 생각하지 말고, 단순하게 차근차근 접근해보는 것도 좋을 것 같다.

'코딩테스트 > SQL - Leetcode' 카테고리의 다른 글

1174. Immediate Food Delivery II  (0) 2024.01.17
1158. Market Analysis I  (0) 2024.01.16
585. Investments in 2016  (0) 2024.01.10
Leetcode SQL Easy난이도 전부 해결!  (0) 2024.01.10
1789. Primary Department for Each Employee  (2) 2024.01.08