SQL
Binary Tree Nodes
sawo11
2025. 5. 5. 20:14
문제 풀이 링크: 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
풀이 방법
- WHERE P IS NOT NULL을 사용하지 않을 경우, NULL 값이 포함될 수 있고, NOT IN 절에 NULL이 포함되면 비교 결과가 항상 FALSE 또는 UNKNOWN이 되어 의도한 결과가 나오지 않게됨
SELECT
N,
CASE
WHEN P IS NULL THEN 'Root'
WHEN N NOT IN (SELECT DISTINCT P FROM BST WHERE P IS NOT NULL) THEN 'Leaf'
ELSE 'Inner'
END AS NodeType
FROM BST
ORDER BY N;