We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Explanation: For leaf Node -
We know that leaf node is parent to none of the node.
The condition will determine whether a node B1.N is not a parent to any other node.
If there is no row in the table where B2.P (parent column) equals B1.N (current node), then the current node is considered a Leaf.
SELECT 1 FROM BST B2 WHERE B2.P = B1.N looks for any child nodes where B1.N appears as a parent.
NOT EXISTS checks if there is no match for a given condition.
Example: For N=1 Go to B2 and check if -
B2.P = 1 -> Does any row in the table have P = 1?
No such row exists.
Hence, 1 is a Leaf.
If no match exists, the node has no children and is therefore a Leaf.
ORDER BY B1.N;
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Binary Tree Nodes
You are viewing a single comment's thread. Return to all comments →
Explanation: For leaf Node - We know that leaf node is parent to none of the node. The condition will determine whether a node B1.N is not a parent to any other node. If there is no row in the table where B2.P (parent column) equals B1.N (current node), then the current node is considered a Leaf.
SELECT 1 FROM BST B2 WHERE B2.P = B1.N looks for any child nodes where B1.N appears as a parent.
NOT EXISTS checks if there is no match for a given condition. Example: For N=1 Go to B2 and check if - B2.P = 1 -> Does any row in the table have P = 1? No such row exists. Hence, 1 is a Leaf.
If no match exists, the node has no children and is therefore a Leaf.
ORDER BY B1.N;