若 root 是 p, q 的 最近公共祖先 ,则只可能为以下情况之一:

p 和 q 在 root 的子树中,且分列 root 的 异侧(即分别在左、右子树中);
p = root ,且 q 在 root 的左或右子树中;
q = root ,且 p 在 root 的左或右子树中;

  • 当 left 和 right 同时为空 :说明 root 的左 / 右子树中都不包含 p,q ,返回 null ;
  • 当 left 和 right 同时不为空 :说明 p, q 分列在 root 的 异侧 (分别在 左 / 右子树),因此 root 为最近公共祖先,返回 root ;
  • 当 left 为空 ,right 不为空 :p,q 都不在 root 的左子树中,直接返回 right 。具体可分为两种情况:
    • p,q 其中一个在 root 的 右子树 中,此时 right 指向 p(假设为 p );
    • p,q 两节点都在 root 的 右子树 中,此时的 right 指向 最近公共祖先节点 ;
  • 当 left 不为空 , right 为空 :与情况 3. 同理

作者:jyd
链接:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/solution/mian-shi-ti-68-ii-er-cha-shu-de-zui-jin-gong-gon-7/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
        // write code here
        TreeNode p = new TreeNode(o1);
        TreeNode q = new TreeNode(o2);

        TreeNode res = helper(root, p, q);
        return res.val;

    }

    public TreeNode helper (TreeNode root, TreeNode p, TreeNode q){
        if(root == null || root.val == p.val || root.val == q.val){
            return root;
        }
        TreeNode left = helper(root.left, p, q);
        TreeNode right = helper(root.right, p, q);

        if(left == null && right == null) return null;
        if(right == null) return left;
        if(left == null) return right;
        return root; // (都非空)

    }
}