SQL/MySQL

[MySQL/HackerRank] Binary Tree Nodes

NLP Developer 2023. 8. 29. 15:58
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.

Code

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
728x90
반응형