CodingSpace

[HackerRank/SQL] Advanced Select - Binary Tree Nodes 본문

HackerRank/SQL

[HackerRank/SQL] Advanced Select - Binary Tree Nodes

개발자_조이킴 2022. 7. 24. 22:15

Problem. Advanced Select - Binary Tree Nodes


Link.

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


Description.

You are given a table, BST, containing two columns: 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

입력 예시
출력 예시
BST 예시


Key Point. 

CASE WHEN,

 

IS,

 

IN,

 

CONCAT,

 

ORDER BY,

 

DISTINCT,


My Answer. 

SELECT
    CASE 
        WHEN P IS NULL THEN CONCAT(N, ' Root')
        WHEN N IN (SELECT DISTINCT SB.P FROM BST SB) THEN CONCAT(N, ' Inner')
        ELSE CONCAT(N, ' Leaf')
    END
FROM BST
ORDER BY N ASC;

References. 

Comments