본문 바로가기
MySQL/문제풀이

[HackerRank] Binary Tree Nodes

by MINNI_ 2021. 3. 23.

1. 문제

 

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:


2. 답

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 bst2 ON bst.n = bst2.p
ORDER BY bst.n
    

3. KEY POINT

 

  • Leaf는 부모가 될 수 없고, Root는 부모가 없다는 성질을 이용
  • CASE문을 이용해 조건에 따라 다른 출력을 할 수 있음

 

www.hackerrank.com/challenges/binary-search-tree-1/problem?h_r=internal-search

 

Binary Tree Nodes | HackerRank

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

www.hackerrank.com

 

댓글