/
LCABinaryTree
69 lines (47 loc) · 1.65 KB
/
LCABinaryTree
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return root;
if(root == p || root == q) return root;
TreeNode left =lowestCommonAncestor(root.left , p ,q);
TreeNode right =lowestCommonAncestor(root.right , p ,q);
if(left!=null && right!= null) return root;
else return (left!=null ?left:right);
}
}
//Iterative Approach
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return root;
HashMap<TreeNode ,TreeNode> parents = new HashMap<>();
Deque<TreeNode> stack = new ArrayDeque<>();
parents.put(root,null);
stack.add(root);
while(!parents.containsKey(p) || !parents.containsKey(q)){
TreeNode node = stack.pop();
if(node.left != null ){
parents.put(node.left,node);
stack.add(node.left);
}if(node.right != null){
parents.put(node.right,node);
stack.add(node.right);
}
}
Set<TreeNode> ancesstor = new HashSet<>();
while(p!= null){
ancesstor.add(p);
p = parents.get(p);
}
while(!ancesstor.contains(q))
q = parents.get(q);
return q;
}
}