250. Count Univalue Subtrees

https://leetcode.com/problems/count-univalue-subtrees/description/

image.png

这道题需要子树所有的VALUE都一致,我们就需要对子树去选队长。如果子树的头头都汇报上来我的部队不一致了,那么上面的头就更不可能一致了。只有左队长 和 右队长 都说一致,然后头在用自己的值分别和左队长右队长比,还一致就可向上汇报一致了。

int cnt = 0;
    public int countUnivalSubtrees(TreeNode root) {
        help(root);
        return cnt;
    }
    private boolean help(TreeNode cur){
        if(cur == null) return true;
        boolean left = help(cur.left);
        boolean right = help(cur.right);
        if(!left || !right) return false;
        int leftv = cur.val;
        if(cur.left != null) leftv = cur.left.val;
        int rightv = cur.val;
        if(cur.right != null) rightv = cur.right.val;
        boolean res = cur.val == leftv && leftv == rightv;
        if(res) cnt++;
        return res;
    }

你可能感兴趣的:(250. Count Univalue Subtrees)