데이터분석가/SQL
[해커랭크] Binary Tree Nodes
chan's chance
2023. 3. 30. 11:22
https://www.hackerrank.com/challenges/binary-search-tree-1/problem?isFullScreen=true
Binary Tree Nodes | HackerRank
Write a query to find the node type of BST ordered by the value of the node.
www.hackerrank.com

위 테이블 BST 를 이용하여 아래와 같이 Root node, Inner node와 Leaf node를 선별하는 문제이다.

문제를 풀기에 앞서 테이블의 특징을 찾기 위해 테이블을 들여다 보니 금방 규칙을 알 수 있었다.
1. 부모 노드가 없는 노드가 Root node이다.
2. 부모 노드에 값이 존재하는 노드는 Inner node이다.
3. 부모 노드에 값이 존재하지 않는 노드는 Leaf node이다.
SELECT N
, CASE WHEN P IS NULL THEN 'Root'
WHEN N IN (SELECT P FROM BST) THEN 'Inner'
ELSE 'Leaf' END AS TYPE
FROM BST
ORDER BY N
코드는 적절히 작성하였으나 ALIAS가 없으면 정답으로 인정하지 않는다.
꼭 ALIAS를 붙여주자!