Skip to content

Commit 2814304

Browse files
authored
Add files via upload
1 parent 9485c04 commit 2814304

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

FindCommonAnscestor.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
//https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/submissions/
2+
public class FindCommonAnscestor {
3+
4+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
5+
//stores the common anscestor
6+
TreeNode ans=new TreeNode();
7+
findAncestor(root,p,q,ans);
8+
return ans;
9+
}
10+
11+
//Traverse the tree through dfs
12+
// if the current node has either value check for children if they have other value if value found in either children or in this node this node is the ancestor
13+
14+
public boolean findAncestor(TreeNode r, TreeNode p, TreeNode q,TreeNode ans) {
15+
if(r!=null) {
16+
//check if this node has value
17+
boolean centre=(r.val==p.val || r.val==q.val);
18+
//check if one value is found in left subtree
19+
boolean left=findAncestor(r.left,p,q,ans);
20+
//check if one value is found in right subtree
21+
boolean right=findAncestor(r.right,p,q,ans);
22+
23+
//if value found in either of 3 combinations set answer with this root value this condition is true only if this is the least common anscestor
24+
if((centre && left) || (centre && right) || (left && right))
25+
ans.val=r.val;
26+
return (left || right || centre);
27+
}
28+
return false;
29+
}
30+
}

0 commit comments

Comments
 (0)