상세 컨텐츠

본문 제목

[오늘의 코드 129] [HackerRank] Binary Tree Nodes

코드 공부

by eun_00 2024. 10. 25. 22:58

본문

[문제]

You are given a table, BST, containing two columns: N and P, where N represents the value of a node in Binary Tree, and P is the parent of N.

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.

Sample Input

[💡 정답]

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 NODE_TYPE
FROM BST
ORDER BY N;
 

 ✔️ 알게된 것 

- N 컬럼은 노드값, P는 부모 값을 의미 

- root: P가 null인 경우
   leaf: 잎은 가지 가장 끝에 있는 것으로 하위 노드를 갖지 않는 경우 (즉, 해당 N 값이 다른 곳에서 P로 참조되지 않는 경우)
   inner: 그 외 나머지 경우

- 각 노드 종류에 따라 조건을 설정하기 위해 CASE WHEN 문을 사용한다.

 

관련글 더보기