LeetCode:236 二叉树的最近公共祖先

class Solution {
    
    private TreeNode res = null;
    
    public boolean dfs(TreeNode root,TreeNode p,TreeNode q){
        if(root==null){
            return false;
        }

        boolean lchild = dfs(root.left,p,q);
        boolean rchild = dfs(root.right,p,q);

        if((lchild&&rchild)||((root.val==p.val||root.val==q.val)&&(lchild||rchild))){
            res = root;
        }

        return lchild||rchild||(root.val==p.val||root.val==q.val);
    }

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root,p,q);
        return res;
    }
}

 

posted @ 2020-10-04 08:46  dlooooo  阅读(73)  评论(0编辑  收藏  举报