其他分享
首页 > 其他分享> > 236. Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree

作者:互联网

When we get this problem, we need to confirm the following 2 questions:

1. Can root, p or q be null? (No)

2. Can p be equal to q? (No)

We look "root" as a pointer, the point will check recursively of it's left and right sub-tree.

If the left return null, the p and q must be in right sub-tree, and if the right return null, the p and q must be in left sub-tree.

But if both left and right are not null, the p and q must be one in left and one in right, the current point should be the result.

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root ==null)
            return null;
        if(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;
        else if(right==null)
            return left;
        else
            return root;

    }

 

标签:Lowest,Binary,right,return,Tree,TreeNode,null,root,left
来源: https://www.cnblogs.com/feiflytech/p/15869972.html