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;
    }
}

 

posted @ 2020-12-25 20:43  不学无墅_NKer  阅读(49)  评论(0编辑  收藏  举报