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

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

2. Are both p and q in the tree (yes)

3. 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;

    }

 

posted on 2022-02-08 06:30  阳光明媚的菲越  阅读(15)  评论(0编辑  收藏  举报