-
Notifications
You must be signed in to change notification settings - Fork 31
/
LeastCommonAncestor.java
55 lines (41 loc) · 939 Bytes
/
LeastCommonAncestor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package Trees;
/**
* Author - archit.s
* Date - 09/11/18
* Time - 4:34 PM
*/
public class LeastCommonAncestor {
static boolean v1 = false, v2 = false;
public TreeNode helper(TreeNode A, int B, int C){
if(A == null){
return null;
}
TreeNode t = null;
if(A.val == B){
v1 = true;
t = A;
}
if(A.val == C){
v2 = true;
t = A;
}
TreeNode left = helper(A.left,B,C);
TreeNode right = helper(A.right,B,C);
if(t!=null){
return t;
}
if(left!=null && right!=null){
return A;
}
return (left!=null) ? left: right;
}
public int lca(TreeNode A, int B, int C) {
v1 = false;
v2 = false;
TreeNode ans = helper(A,B,C);
if(v1 && v2){
return ans.val;
}
return -1;
}
}