Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding left most node in a binary tree

I need to find the left most node in a binary tree. It may sound naive but it isnt. I tried this but i think it will fail :

Node* findLeftMostNode(Node* root){
    if(root->left==null)
       return root;
    findLeftMostNode(root->left);
}

The problem is that the left mode node can be at any level so we need to handle that.

          X
          \
           X
           /\
          X  X
         /
        X
       /
      X
like image 371
h4ck3d Avatar asked Aug 08 '26 19:08

h4ck3d


1 Answers

With this way of calculating the “leftness” of a node, you always have to recurse to both child nodes, because any child could contain a sequence of n nodes going left for any n.

So, the solution is actually quite simple: calculate the x for each node in the tree and return the smallest one:

Node* findLeftmostNode(Node* current, int x = 0)
{
    current->x = x;

    Node* best;
    // leftmost child in the left subtree is always better than the root
    if (current->left == null)
        best = current;
    else
        best = findLeftmostNode(current->left, x - 1);

    if (current->right != null)
    {
        Node* found = findLeftmostNode(current->right, x + 1);
        if (found->x < best->x)
            best = found;
    }

    return best;
}
like image 188
svick Avatar answered Aug 11 '26 10:08

svick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!