Data/HackerRank

HackerRank - Binary Tree Nodes

corycory 2022. 3. 2. 21:14
728x90
반응형

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

 

문제

 

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:

 

 

풀이

위 그림 처럼, P가 없으면 Root, P가 있으면서 자기도 다른 노드의 P가 되면 Inner, P만 있는 경우는 Leaf 로 구분하면 된다. 간단하게는, P 리스트를 만들고, 노드가 P가 없으면 Root, P리스트 안에 자신의 값이 있으면 Inner, 그 외는 Leaf로 구분하는 코드를 짜면 된다. 

 

/*
Enter your query here.
*/

select n,
case 
    when p is null then 'Root'
    when n in (select distinct p from bst) then 'Inner'
    else 'Leaf'
end as node_type
from bst
order by n

 

반응형

'Data > HackerRank' 카테고리의 다른 글

HackerRank - Challenges  (0) 2022.03.02
HackerRank - Weather Observation Station 20  (0) 2022.03.02
HackerRank - The PADS  (0) 2022.03.01
HackerRank - Ollivander's  (0) 2022.03.01
HackerRank - Interviews  (0) 2022.03.01