Hacker Rank SQL

Binary Tree Nodes Solution

Hello Friends in this article i am gone to share Hacker Rank SQL Solutions with you | Binary Tree Nodes Solution


Also Visit:ย  Occupations Solution


 

Problem

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.

Column Type
N Integer
P Integer

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

N P
1 2
3 2
6 8
9 8
2 5
8 5
5 null

Sample Output

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

 

Solution โ€“ Binary Tree Nodes Solution

MySQL Code
SELECT N, IF(P IS NULL,"Root",
IF((SELECT COUNT(*) FROM BST WHERE P=B.N)>0,"Inner","Leaf")) 
FROM BST AS B ORDER BY N;

 


What is Binary Tree Data Structure?

Binary Tree is defined as a tree data structure where each node has at most 2 children. Since each element in a binary tree can have only 2 children, we typically name them the left and right child.

Binary Tree Representation

A Binary tree is represented by a pointer to the topmost node (commonly known as the โ€œrootโ€) of the tree. If the tree is empty, then the value of the root is NULL. Each node of a Binary Tree contains the following parts:

  • Data
  • Pointer to left child
  • Pointer to right child

Basic Operation On Binary Tree:

  • Inserting an element.
  • Removing an element.
  • Searching for an element.
  • Traversing the tree.

Auxiliary Operation On Binary Tree:

  • Finding the height of the tree
  • Find the level of a node of the tree
  • Finding the size of the entire tree.

 

 

Disclaimer: The above Problems are generated by Hacker Rank but the Solutions are Provided by NYANDER.COM. All Hacker Rank SQL Solutions Shared only for Educational and Learning Purpose.