HAZEL

[SQL : HackerRank] Binary Tree Nodes 본문

DATA ANALYSIS/SQL

[SQL : HackerRank] Binary Tree Nodes

Rmsid01 2021. 3. 3. 13:24

Binary Tree Nodes


>> 문제

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

Sample Output

1 Leaf

2 Inner

3 Leaf

5 Root

6 Leaf

8 Inner

9 Leaf


Explanation

The Binary Tree below illustrates the sample:

 

 

>> 문제푼 코드

SELECT distinct BST.N
    , CASE
        WHEN BST.P IS NULL THEN 'Root'
        WHEN BST2.N IS NULL THEN 'Leaf'
        ELSE 'Inner'
     END
FROM BST
    LEFT JOIN BST AS BST2 
        ON BST.N = BST2.P
ORDER BY BST.N

 

※ 이 문제에서는 case문을 떠올려서 푸는 것이 중요하다! 

join 으로 얻어낸 값 자체도 case로 할 수 있다.  배운건 잊지말고 생각하자! 

 

 

www.hackerrank.com/challenges/binary-search-tree-1/problem

 

Binary Tree Nodes | HackerRank

Write a query to find the node type of BST ordered by the value of the node.

www.hackerrank.com