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;

'SQL' 카테고리의 다른 글

The Report  (0) 2025.05.05
Contest Leaderboard  (0) 2025.05.05
Weather Observation Station 19  (0) 2025.05.05
Draw The Triangle1, 2  (0) 2025.05.05
The Blunder  (0) 2025.05.05