剑指 Offer 68 - II. 二叉树的最近公共祖先

题目链接:

力扣icon-default.png?t=M4ADhttps://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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值