(1) 递归:
写一个函数:判断以root为根节点的子树中是否含有p和q节点
有两种情况:p q分别在左右子树上;
p q在同一个子树上,此时root节点是其中一个
利用回溯特性,root是深度最深的公共节点
private TreeNode ans;
public boolean dfs(TreeNode root, TreeNode p, TreeNode q){
if(root == null) return false;
boolean lson = dfs(root.left, p, q);
boolean rson = dfs(root.right, p, q);
if((lson && rson) || ((root.val == p.val || root.val == q.val) && (lson || rson)) ){
this.ans = root;
}
return lson || rson || root.val == p.val || root.val == q.val;
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
dfs(root, p, q);
return this.ans;
}
时间 O(N)
空间O(n)
(2)存储路径
HashMap<Integer, TreeNode> mapFather = new HashMap<Integer, TreeNode>();
Set<Integer> visited = new HashSet<Integer>();
public void dfs(TreeNode root){
if(root.left != null){
mapFather.put(root.left.val, root);
dfs(root.left);
}
if(root.right != null){
mapFather.put(root.right.val, root);
dfs(root.right);
}
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
dfs(root);
while(p != null){
visited.add(p.val);
p = mapFather.get(p.val);
}
while(q != null){
if(visited.contains(q.val)){
return q;
}
q = mapFather.get(q.val);
}
return root;
}