-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_0235LowestCommonAncestorOfABinarySearchTree.java
81 lines (73 loc) · 2.51 KB
/
_0235LowestCommonAncestorOfABinarySearchTree.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
package com.heatwave.leetcode.problems;
import java.util.LinkedList;
import java.util.List;
public class _0235LowestCommonAncestorOfABinarySearchTree {
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (p.val == root.val || q.val == root.val) {
return root;
}
if ((p.val < root.val && q.val > root.val) || (p.val > root.val && q.val < root.val)) {
return root;
}
if (p.val < root.val) {
return lowestCommonAncestor(root.left, p, q);
}
return lowestCommonAncestor(root.right, p, q);
}
}
class AnotherSolution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (p.val < root.val && q.val < root.val) {
return lowestCommonAncestor(root.left, p, q);
} else if (p.val > root.val && q.val > root.val) {
return lowestCommonAncestor(root.right, p, q);
}
return root;
}
}
class SolutionTwiceTraversal {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
List<TreeNode> pPath = getPath(root, p);
List<TreeNode> qPath = getPath(root, q);
int i = 0;
while (i < pPath.size() && i < qPath.size()) {
if (pPath.get(i) != qPath.get(i)) {
break;
}
i++;
}
return pPath.get(i - 1);
}
private List<TreeNode> getPath(TreeNode node, TreeNode p) {
List<TreeNode> path = new LinkedList<>();
while (true) {
path.add(node);
if (node == p) {
break;
}
if (p.val < node.val) {
node = node.left;
} else {
node = node.right;
}
}
return path;
}
}
class SolutionOnceTraversal {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode ans = root;
while (true) {
if (p.val < ans.val && q.val < ans.val) {
ans = ans.left;
} else if (p.val > ans.val && q.val > ans.val) {
ans = ans.right;
} else {
break;
}
}
return ans;
}
}
}