Binary Tree Nodes SQl – Hacker Rank Solution

Binary Tree Nodes - Hacker Rank Solution
Binary Tree Nodes – Hacker Rank Solution

Problem

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.

1443818507 5095ab9853 1

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

1443818467 30644673f6 2

Sample Output

1 Leaf
2 Inner
3 Leaf
5 Root
6 Leaf
8 Inner
9 Leaf


Explanation

The Binary Tree below illustrates the sample:

1443773633 f9e6fd314e simply sql bst


Binary Tree Nodes SQL – Hacker Rank Solution

SELECT BT.N,
CASE
    WHEN BT.P IS NULL THEN 'Root'
    WHEN EXISTS (SELECT B.P FROM BST B WHERE B.P = BT.N) THEN 'Inner'
    ELSE 'Leaf'
END
FROM BST AS BT
ORDER BY BT.N

Disclaimer: The above Problem (Binary Tree Nodes) generated by Hackerrank but the Solution is Provided by Chase2Learn. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the following contact form thank you.

Leave a Comment