LeetCode236. 二叉树的最近公共祖先

☆☆☆思路:经典的LCA问题

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        if (p == root || q == root) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) return root; // p 和 q在不同的子树中
        if (left != null) return left;
        if (right != null) return right;
        return null;
    }
}
原文地址:https://www.cnblogs.com/HuangYJ/p/14189514.html