LC250. Count Univalue Subtrees

Posted by freeCookie🍪 on January 18, 2017

LC250. 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.

recursion + 全局变量

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int count = 0;
    public int countUnivalSubtrees(TreeNode root) {
        if(root == null)    return 0;
        helper(root);
        return count;
    }
    
    private boolean helper(TreeNode root){
        if(root == null)    return true;
        boolean left = helper(root.left);
        boolean right = helper(root.right);
        if(left && right){
            if(root.left != null && root.left.val != root.val)  return false;
            if(root.right != null && root.right.val != root.val)    return false;
            count++;
            return true;
        }
        return false;
    }
    
}

O(n), O(height)