Skip to content

Commit 8547dc0

Browse files
authored
236. lowest Common Ancestor of A Binary tree
1 parent deaca8d commit 8547dc0

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
//Same as Binary search tree
2+
3+
if(!root)return NULL;
4+
5+
//Base Case
6+
if(root->val == p->val)return p;
7+
if(root->val == q->val)return q;
8+
9+
//Recursion
10+
TreeNode* leftans = lowestCommonAncestor(root->left,p,q);
11+
TreeNode* rightans = lowestCommonAncestor(root->right,p,q);
12+
13+
if(!leftans && !rightans)return NULL;
14+
else if(!leftans && rightans)return rightans;
15+
else if(leftans && !rightans)return leftans;
16+
else{
17+
return root;
18+
}

0 commit comments

Comments
 (0)