-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCA.java
More file actions
68 lines (53 loc) · 1.39 KB
/
Copy pathLCA.java
File metadata and controls
68 lines (53 loc) · 1.39 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
package dummypkg;
import java.util.ArrayList;
public class LCA {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root=new TreeNode(1);
root.left=new TreeNode(2);
root.right=new TreeNode(3);
root.left.left=new TreeNode(4);
root.left.right=new TreeNode(5);
root.left.right.left=new TreeNode(6);
System.out.print(lca(root, 6, 6));
}
public static int lca(TreeNode a, int x, int y) {
ArrayList<Integer> alx=new ArrayList<>();
ArrayList<Integer> aly=new ArrayList<>();
fun( a, x, alx);
fun( a, y, aly);
int i, min=Math.min(alx.size(), aly.size());
for(i=0; i<min; i++) {
if(alx.get(i)!=aly.get(i))
break;
}
if(i==0)
return -1;
else
return (alx.size()<aly.size())?alx.get(i-1):aly.get(i-1);
}
public static boolean fun(TreeNode a, int x, ArrayList<Integer> al) {
if(a==null) return false;
al.add(a.val);
boolean resA=false, resB=false;
if(a.val==x) return true;
if(a.left!=null) {
resA=fun(a.left, x, al);
}
if(a.right!=null && !resA) {
resB= fun(a.right, x, al);
}
if(resA||resB) {
return true;
} else {
al.remove(al.size()-1);
return false;
}
}
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}