[LeetCode] 608. Tree Node

bin·2023년 1월 17일
0

608. Tree Node

https://leetcode.com/problems/tree-node/

Requirements

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.
Return the result table in any order.
The query result format is in the following example.

💡IN / SubQuery / CASE WHEN 구문을 활용한다.

  • p_id가 null이라면 최상단 노드이다.
  • p_id로 등록된 id는 자식 노드를 가진 부모 노드이다.
  • p_id로 등록되지 않은 id는 부모 노드를 가진 자식 노드이다.

Solution

SELECT id, 
    CASE WHEN p_id IS NULL THEN 'Root'
        WHEN id IN (SELECT p_id FROM Tree) THEN 'Inner'
        ELSE 'Leaf'
    END AS type
FROM Tree 

⚠️ SubQuery는 성능 저하를 야기할 수 있습니다. 내부 JOIN을 이용한 풀이를 고안해봐야겠습니다.

0개의 댓글