Binary Tree Nodes

  • + 0 comments
    SELECT
        B1.N,
        CASE
            WHEN B1.P IS NULL THEN "Root"
            WHEN NOT EXISTS (SELECT 1 FROM BST B2 WHERE B2.P = B1.N) THEN 'Leaf'
            ELSE "Inner"
        END AS NodeType
    FROM 
        BST B1 
    ORDER  
    	BY B1.N;
    

    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;