-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path235. Lowest Common Ancestor of a Binary Search Tree.java
81 lines (81 loc) · 2.4 KB
/
235. Lowest Common Ancestor of a Binary Search Tree.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
// to solve this problem we need to get the node to root path of both p and q
// if p and q are on the same side of root, then LCA is root
// find the node p
List<TreeNode> nodepathP = find(root, p);
// find the node q
List<TreeNode> nodepathQ = find(root, q);
TreeNode result = null;
int i = nodepathP.size() - 1;
int j = nodepathQ.size() - 1;
while (ensureNotOutOfBound(i, j) && matchBothNode(nodepathP, nodepathQ, i, j)) {
result = nodepathP.get(i);
i--;
j--;
}
return result;
}
private boolean matchBothNode(List<TreeNode> nodepathP, List<TreeNode> nodepathQ, int i, int j) {
return nodepathP.get(i) == nodepathQ.get(j);
}
private boolean ensureNotOutOfBound(int i, int j) {
return i >= 0 && j >= 0;
}
private List<TreeNode> find(TreeNode root, TreeNode node) {
if (root == null)
return new ArrayList<>();
if (root.val == node.val) {
List<TreeNode> bbres = new ArrayList<TreeNode>();
bbres.add(node);
return bbres;
}
List<TreeNode> nodepath = new ArrayList<TreeNode>();
// faith
List<TreeNode> rresFromLeft = find(root.left, node);
if (rresFromLeft.size() > 0) {
return addIfNodeFound(root, nodepath, rresFromLeft);
}
List<TreeNode> rresFromRight = find(root.right, node);
if (rresFromRight.size() > 0) {
return addIfNodeFound(root, nodepath, rresFromRight);
}
return nodepath;
}
private List<TreeNode> addIfNodeFound(TreeNode root, List<TreeNode> nodepath, List<TreeNode> rresFromLeft) {
nodepath.addAll(rresFromLeft);
nodepath.add(root);
return nodepath;
}
}