LC.P236[二叉树的最近公共祖先]

方法一:DFS+回溯

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
List<TreeNode> a = new ArrayList<>(), b = new ArrayList<>();
dfs(root, p, a);
dfs(root, q, b);
TreeNode ans = null;
for (int i = 0; i < Math.min(a.size(), b.size()) && a.get(i) == b.get(i); ++i) {
ans = a.get(i);
}
return ans;
}

private boolean dfs(TreeNode cur, TreeNode target, List<TreeNode> path) {
if (cur == null) return false;
path.add(cur);
if (cur == target || dfs(cur.left, target, path) || dfs(cur.right, target, path)) {
return true;
} else {
path.remove(path.size() - 1);
return false;
}
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

方法二:DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
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 && right == null) return null;
if(left == null) return right;
if(right == null) return left;
return root; // left != null and right != null
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$