Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
667 B
2
Indexable
Never
TreeNode<int>* solve(TreeNode<int> *root, int x, int y){
    if(root==NULL) return NULL;
    if(root->data==x) return root;
    if(root->data==y) return root;

 
    TreeNode<int>* left = solve(root->left,x,y);
    TreeNode<int>* right= solve(root->right,x,y);
    
    if(left!=NULL && right!=NULL) return root;
    else if(left!=NULL && right==NULL) return left;
    else if(left==NULL && right!=NULL) return right;
    else if(left==NULL && right==NULL) return NULL;
    //return NULL;
}

int lowestCommonAncestor(TreeNode<int> *root, int x, int y) //it's only BT not BST!!
{
	TreeNode<int>* ans=solve(root,x,y);
    return ans->data;
}