# Binary Tree Nodes SQl Hacker Rank Solution

Hello coders, In this post, you will learn how to solve the Binary Tree Nodes SQl Hacker Rank Solution. This problem is a part of the SQL Hacker Rank series.

### 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.

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:

### 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.

Sharing Is Caring