HackerRank-AdvancedSelect-Binary Tree Nodes
Binary Tree Nodes
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.
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:
My solution
SELECT DISTINCT(bst1.N), CASE WHEN bst1.P IS NULL THEN 'Root'
WHEN bst2.N IS NULL THEN 'Leaf'
ELSE 'Inner'
END
FROM BST bst1 LEFT OUTER JOIN BST bst2
ON bst1.N=bst2.P
ORDER BY bst1.N ASC;
Most vote solution
SELECT 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;
Comments