SQL & DB/HackerRank SQL Problem

[HackerRank SQL] Binary Tree Nodes

YSY^ 2021. 2. 27. 18:17

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

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:


Answer

select 
    N,
    case when p is null  then 'Root' #Root 는 p(parent)가 없다(null)
        when N in (select P from BST) then 'Inner'  # root도 아니고 P에도 포함된다면 inner이다.
        else 'Leaf'
        end
from BST
order by N

 

Result

728x90
반응형

'SQL & DB > HackerRank SQL Problem' 카테고리의 다른 글

[HackerRank SQL] The Blunder  (0) 2021.02.27
[HackerRank SQL] New Companies (MySQL)  (0) 2021.02.27
[HackerRank SQL] Occupations  (0) 2021.02.27
[HackerRank SQL] The PADS (MySQL)  (0) 2021.02.27
[HackerRank SQL] Type of Triangle  (0) 2021.02.27