SQL : Binary Tree Nodes Problem

 Hello All,

We are back with another SQL problem, focusing on use case of SQL CASE statement. CASE statement works similar to that of IF - ELSE ladder in other programming languages. This problem requires use of CONCAT() function.

You can visit following learning resources related to this particular question :

1. SQL CASE statement - SQL CASE Statement (w3schools.com)

2. concat function - CONCAT (Transact-SQL) - SQL Server | Microsoft Docs 

The problem below is sourced from HackerRank. You can visit the link: Binary Tree Nodes | HackerRank

Give a try to solve below problem. Solution is provided as usual. Feel free to comment if any queries and also suggest alternate approach to solve this problem. Have a Happy Learning !  

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

Solution :


SELECT DISTINCT N,
(CASE WHEN P IS NULL THEN "Root"
            WHEN N IN (SELECT DISTINCT P FROM BST) THEN "Inner"
             ELSE "Leaf"
END)
FROM BST
ORDER BY N

Explanation :

If you observe the table carefully, you will notice that ROOT is the one with null parent node P. After ROOT is selected, INNER is the one in N which is present in P. And remaining everything is LEAF.
So, we have used CASE statement along with SELECT to present these 3 cases. And rest is done as usual !
 

Comments

Popular posts from this blog

SQL for beginners : finding out Employees Earning More Than Their Managers

Answer to SQL Leetcode Question 183. Customers Who Never Order

SQL Medium difficulty practice question : Consecutive Numbers