728x90
문제
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.
https://www.hackerrank.com/challenges/binary-search-tree-1/problem?isFullScreen=true
예시
input
output
1 Leaf
2 Inner
3 Leaf
5 Root
6 Leaf
8 Inner
9 Leaf
문제 풀이
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
FROM
bst
ORDER BY
n;
SQL을 독학하시는 분들에게 도움이 되길 바라며,
혹 더 좋은 방법이 있거나 오류가 있다면 편하게 말씀 부탁드립니다.
728x90