其他分享
首页 > 其他分享> > 二叉树的最近公共祖先

二叉树的最近公共祖先

作者:互联网

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || p == root || q == root) {
            return root;
        }

        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);

        if(left==null){
            return right;
        }else if(right==null){
            return left;
        }else{
            return root;
        }
    }

 

标签:lowestCommonAncestor,right,TreeNode,祖先,二叉树,公共,return,root,left
来源: https://www.cnblogs.com/shijianchuzhenzhi/p/15971354.html