Binary Tree Nodes

  • + 0 comments

    MySQL Solution

    Logic:

    1. If the parent node corresponding to a node is 'NULL' -> It is the root node.
    2. Else if the node is a part of the parent as well as the node columns, it means that the node has a child as well as a parent. So -> this is an inner node.
    3. Else all other nodes will be the leaf nodes because they have a parent node but no child nodes.

    Code:

    select N,
    case when P is NULL then 'Root'
    when N in (select P from BST) then 'Inner'
    else 'Leaf'
    end 
    from BST
    order by N;