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.
/* This SQL query classifies each node in a Binary Tree based on its type and outputs the result ordered by the node value. The node types are classified as follows: - Root: A node that does not have a parent (P is NULL). - Leaf: A node that does not have any children (does not appear in the P column of any other node). - Inner: A node that has a parent and has at least one child. Query Breakdown: 1. Main Query: - Selects the node value (N) and applies a CASE statement to determine the type of the node. 2. CASE Statement: - WHEN P IS NULL THEN 'Root': Identifies nodes with no parent as Root. - WHEN N NOT IN (SELECT DISTINCT P FROM BST WHERE P IS NOT NULL) THEN 'Leaf': Identifies nodes that do not appear as parents of any other nodes as Leaf. - ELSE 'Inner': Nodes that are neither Root nor Leaf are classified as Inner. 3. Subquery: - (SELECT DISTINCT P FROM BST WHERE P IS NOT NULL): Retrieves all distinct parent nodes (excluding NULL) to help determine if a node is a leaf. 4. ORDER BY N: - Orders the results by the node value (N). The result provides the type of each node in the binary tree in ascending order of node values. SQL Query:*/SELECTN,CASEWHENPISNULLTHEN'Root'WHENNNOTIN(SELECTDISTINCTPFROMBSTWHEREPISNOTNULL)THEN'Leaf'ELSE'Inner'ENDASNodeTypeFROMBSTORDERBYN;
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 →
Hope this helps.