Binary Search Tree : Lowest Common Ancestor

  • + 0 comments

    C++ solution

    // Check if given data is present in given node or not
        bool search(Node *root, int data)
        {
            while(root != nullptr)
            {
                if(root->data == data)
                {
                    return true;
                }
                else if(data < root->data)
                {
                    root = root->left;
                }
                else
                {
                    root = root->right;
                }
            }
            return false;
        }
      
        Node *lca(Node *root, int v1,int v2) {
    		stack<Node*> s;
            Node *temp = root;
            
            // searching for v1 and storing its path in stack
            while(temp != nullptr)
            {
                s.push(temp);
                if(temp->data == v1)
                {
                    break;
                }
                else if(v1 < temp->data)
                {
                    temp = temp->left;
                }
                else
                {
                    temp = temp->right;
                }
            }
            // search complete
    
            // search for v2 in each ancestor of v1
            while(!s.empty())
            {
                if(search(s.top(), v2))
                {
                    Node *ans = s.top();
                    return ans;
                }
                s.pop();
            }
            
            return nullptr;
            
        }