leetcode 236. Lowest Common Ancestor of a Binary Tree

看看什么是最低共同祖先,就是第一个左右分别存在p和q的节点

还是正常dfs,当遇到null返回null,遇到p返回p,遇到q返回q

若left 和 right 都不为null则说明这就是我们要找的节点

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q)
            return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left != null && right != null)
            return root;
        return left == null ? right : left;
    }
}

 

posted @ 2019-08-16 01:58  南山南北秋悲  阅读(97)  评论(0编辑  收藏  举报