OkBublewrap

Binary Tree Nodes 본문

개발/SQL

Binary Tree Nodes

옥뽁뽁 2025. 1. 10. 14:07

Binary Tree Nodes

문제 설명

Write a query to find the node type of Binary Tree ordered by the value of the node. Output one of the following for each node:

Root: If node is root node.
Leaf: If node is leaf node.
Inner: If node is neither root nor leaf node.


입력 테이블

  1. BST
    • N
    • P

풀이

SELECT 
    N,
    CASE
        WHEN P IS NULL THEN 'Root'                
        WHEN N NOT IN (SELECT P FROM BST WHERE P IS NOT NULL) THEN 'Leaf' 
        ELSE 'Inner'                             
    END AS NodeType
FROM BST
ORDER BY N;      

해석

  1. 부모 노드 P이 NULL 이면 Root
  2. 부모 노드 P가 NULL이 아니고, 있는 N (자식노드) 이면 Leaf
  3. 그것도 아니면 Inner