236 Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree

1. Question

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to thedefinition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
1
_______3______
2
/ \
3
___5__ ___1__
4
/ \ / \
5
6 _2 0 8
6
/ \
7
7 4
Copied!
For example, the lowest common ancestor (LCA) of nodes5and1is3. Another example is LCA of nodes5and4is5, since a node can be a descendant of itself according to the LCA definition.

2. Implementation

(1) Recursion
1
class Solution {
2
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
3
if (root == null || root == p || root == q) {
4
return root;
5
}
6
7
TreeNode left = lowestCommonAncestor(root.left, p, q);
8
TreeNode right = lowestCommonAncestor(root.right, p, q);
9
10
if (left != null && right != null) {
11
return root;
12
}
13
return left != null ? left : right;
14
}
15
}
Copied!
(2) Iteration
1
class Solution {
2
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
3
Map<TreeNode, TreeNode> parent = new HashMap<>();
4
Stack<TreeNode> stack = new Stack<>();
5
6
parent.put(root, null);
7
stack.push(root);
8
9
while (!parent.containsKey(p) || !parent.containsKey(q)) {
10
TreeNode curNode = stack.pop();
11
12
if (curNode.left != null) {
13
parent.put(curNode.left, curNode);
14
stack.push(curNode.left);
15
}
16
17
if (curNode.right != null) {
18
parent.put(curNode.right, curNode);
19
stack.push(curNode.right);
20
}
21
}
22
23
Set<TreeNode> ancestor = new HashSet<>();
24
while (p != null) {
25
ancestor.add(p);
26
p = parent.get(p);
27
}
28
29
while (!ancestor.contains(q)) {
30
q = parent.get(q);
31
}
32
return q;
33
}
34
}
Copied!

3. Time & Space Complexity

Recursion: 时间复杂度O(n), 空间复杂度O(h)
Iteration: 时间复杂度O(n), 空间复杂度O(h)