Count Univalue Subtrees

Given a binary tree, count the number of uni-value subtrees.

A Uni-value subtree means all nodes of the subtree have the same value.

For example:
Given binary tree,
              5
             / \
            1   5
           / \   \
          5   5   5
return 4.

    int sum = 0;

    public int countUnivalSubtrees(TreeNode root) {
        if(Helper(root)) sum ++;
        return sum;
    }

    private boolean Helper(TreeNode root){
        if(root == null) return false;
        else if(root.left == null && root.right == null){
            return true;
        }else{
            boolean isSame = true;
            if(root.left != null) {
                boolean left = Helper(root.left);
                if(left) sum ++;
                if(!left || root.val != root.left.val) isSame = false;
            }
            if(root.right != null) {
                boolean right = Helper(root.right);
                if(right) sum ++;
                if(!right || right && root.val != root.right.val) isSame = false;
            }
            return isSame;
        }
    }

results matching ""

    No results matching ""