-
Notifications
You must be signed in to change notification settings - Fork 0
/
LowestCommonAncestorOfABinaryTree.java
46 lines (41 loc) · 1.18 KB
/
LowestCommonAncestorOfABinaryTree.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean findPath(TreeNode root, TreeNode p, Deque<TreeNode> path) {
if (root == null) {
return false;
}
path.addLast(root);
if (root.val == p.val) {
return true;
}
if (findPath(root.left, p, path)) {
return true;
}
if (findPath(root.right, p, path)) {
return true;
}
path.removeLast();
return false;
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
Deque<TreeNode> pPath = new LinkedList<>();
Deque<TreeNode> qPath = new LinkedList<>();
findPath(root, p, pPath);
findPath(root, q, qPath);
TreeNode result = null;
while (pPath.peekFirst() == qPath.peekFirst() && pPath.peekFirst() != null) {
result = pPath.peekFirst();
pPath.removeFirst();
qPath.removeFirst();
}
return result;
}
}