二叉树的最近公共祖先

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    // p ,q 都在左子树
    if(contains(root.left,p) && contains(root.left,q)){
        return lowestCommonAncestor(root.left,p,q);
    }
    // p,q 都在右子树
    if(contains(root.right,p) && contains(root.right,q)){
        return lowestCommonAncestor(root.right,p,q);
    }
    return root;
}

//判断以root 为根节点二叉树是否包含 p 节点
private boolean contains(TreeNode root,TreeNode p){
    if(root==null || p==null){
        return false;
    }
    if(root.val == p.val){
        return true;
    }
    return contains(root.left,p) || contains(root.right,p);
}
//思路二: 
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root == null){
        return null;
    }
    //如果 p或者是q是根节点,那么该root就是他们最近的公共父节点
    if(p== root || q==root){
        return root;
    }
    
    //   1
    //  / \
    // 2   3
    // 其中 p 为 2,q 为 3 则 left=p,right=q
    //显然 root 为 p、q 的最近公共祖先
    //p,q 在左子树中是否有公共父节点
    TreeNode left = lowestCommonAncestor(root.left,p,q);
    //p,q 在右子树中是否有公共父节点
    TreeNode right = lowestCommonAncestor(root.right,p,q);
    if(left!=null && right!=null){
        return root;
    }
    if(left != null){
        return left;
    }
    if(right != null){
        return right;
    }
    return null;
}

https://www.mianshi.onlinehttps://www.i9code.cn

本文由博客一文多发平台 OpenWrite 发布!

逃跑的眼镜_bvbEK5
7 声望0 粉丝