Binary Tree Nodes

  • + 0 comments

    -- Define the root CTE to find nodes with no parent

    WITH root AS ( SELECT DISTINCT N FROM BST WHERE P IS NULL ),

    -- Define the inner_node CTE to find nodes that are parents of other nodes -- but are not classified as roots

    inner_node AS ( SELECT DISTINCT P FROM BST
    WHERE P NOT IN (SELECT N FROM root) ),

    -- Define the leaf CTE to find nodes that are not parents of any nodes -- and have a parent (i.e., P is not NULL)

    leaf AS ( SELECT DISTINCT N FROM BST WHERE N NOT IN (SELECT P FROM inner_node) AND P IS NOT NULL )

    -- Combine results from all three CTEs and classify nodes as 'Root', 'Inner', or 'Leaf'

    SELECT N, 'Root' FROM root

    UNION ALL

    SELECT P, 'Inner' FROM inner_node

    UNION ALL

    SELECT N, 'Leaf' FROM leaf

    -- Order the final result by node value ORDER BY 1;