Poison

236. Lowest Common Ancestor of a Binary Tree

Recursion
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root;
}

TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left == null) {
return right;
} else if (right == null) {
return left;
} else {
return root;
}
}
}
Iterate
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
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
Map<TreeNode, TreeNode> childToParentMap = new IdentityHashMap<>();
Set<TreeNode> parentSet = new HashSet<>();

dfs(root, null, childToParentMap);

while (p != null) {
parentSet.add(p);
p = childToParentMap.get(p);
}

while (q != null) {
if (parentSet.contains(q)) {
return q;
}
q = childToParentMap.get(q);
}

return null;
}

private void dfs(TreeNode node, TreeNode parent, Map<TreeNode, TreeNode> childToParentMap) {
if (node == null) {
return;
}

childToParentMap.put(node, parent);
dfs(node.left, node, childToParentMap);
dfs(node.right, node, childToParentMap);
}
}
Reference

236. Lowest Common Ancestor of a Binary Tree
剑指 Offer 68 - II. 二叉树的最近公共祖先