-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLCA.java
61 lines (45 loc) · 1.1 KB
/
LCA.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
56
57
58
59
60
61
// Java Program for Lowest Common Ancestor in a Binary Tree
import java.util.ArrayList;
import java.util.List;
class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
public class LCA {
Node root;
private List<Integer> path1 = new ArrayList<>();
private List<Integer> path2 = new ArrayList<>();
boolean findPath(Node root, int n, List<Integer> path) {
if (root == null) {
return false;
}
path.add(root.data);
if (root.data == n) {
return true;
}
if ((root.left != null && findPath(root.left, n, path))
|| (root.right != null && findPath(root.right, n, path))) {
return true;
}
path.remove(path.size() - 1);
return false;
}
int findLCA(Node root, int n1, int n2) {
path1.clear();
path2.clear();
if (!findPath(root, n1, path1) || !findPath(root, n2, path2)) {
return -1;
}
int i=0;
while (i<path1.size() && i < path2.size()){
if (!path1.get(i).equals(path2.get(i)))
break;
i+=1;
}
return path1.get(i - 1);
}
}//GeeksforGeeks