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;

    }

 

上一篇:JZ55二叉树的深度C++


下一篇:1644. Lowest Common Ancestor of a Binary Tree II