剑指 Offer 68 - II. 二叉树的最近公共祖先

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q) return root;
        TreeNode leftNode = lowestCommonAncestor(root.left,p,q);
        TreeNode rightNode = lowestCommonAncestor(root.right,p,q);

        //1、root 的 左右子树都不包含p、q,返回null
        if(leftNode == null && rightNode == null) return null;
        //2、p、q分列 root的左、右子树中。因此root是最近公共祖先,返回root
        if(leftNode != null && rightNode != null) return root;//多余了
        //3、左子树为空,右子树不为空,说明p、q都在右子树中,返回right
        if(leftNode == null && rightNode != null) return rightNode; // if(leftNode == null) return rightNode;
        //4、同3
        if(leftNode != null && rightNode == null) return leftNode;  // if(rightNode == null) return leftNode;
        return root;
    }
}

 

posted @ 2020-12-18 11:57  peanut_zh  阅读(111)  评论(0编辑  收藏  举报