题目链接:
力扣https://leetcode.cn/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/
【分析】dfs自下向上搜索:
1.如果当前节点为null直接返回
2.如果当前节点为p或者q,说明另一个一定是当前节点的left或者right,那么当前节点就是公共祖先,直接返回
3.递归遍历left和right,如果left为null,说明公共节点肯定在right上或者没有,返回right即可;
如果right为null,说明公共节点在left上或者没有,返回left;
如果二者都不为null,说名p和q分居两侧,返回root。
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;
if(right == null) return left;
return root;
}
}
是不是不太好理解,没关系我们看一个比较臃肿的写法,把每一种可能性都考虑一下:
1.root为null,空树,直接返回
2.递归遍历left和right
3.如果root为p:left或者right任意一个为q,则root为答案,否则返回root
如果root为q:left或者right任意一个为p,则root为答案,否则返回root(这里返回root是为了给上一层做判断用)
4.如果left为p:right必须为q,root才为答案,否则返回left
如果left为q:right必须为p
5.如果right为q:left必须为p
如果right为p:left必须为q
需要注意:如果当前root不是答案,那么也要将当前已经找到的p或者q返回,给上一层做参考用。
class Solution {
public TreeNode ans = null;
TreeNode p, q;
public TreeNode dfs(TreeNode node){
if(node == null) return null;
TreeNode left = dfs(node.left);
TreeNode right = dfs(node.right);
if(node == p){
if(left == q || right == q) {
ans = node; return null;
}else{
return node;
}
}else if(node == q){
if(left == p || right == p){
ans = node; return null;
}else{
return node;
}
}
if(left == p){
if(right == q){
ans = node; return null;
}else{
return left;
}
}else if(left == q){
if(right == p){
ans = node; return null;
}else{
return left;
}
}else if(right == p){
if(left == q){
ans = node; return null;
}else{
return right;
}
}else if(right == q){
if(left == p){
ans = node; return null;
}else{
return right;
}
}else{
return null;
}
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
this.p = p;
this.q = q;
dfs(root);
return ans;
}
}