250. Count Univalue Subtrees (A Uni-value subtree means all nodes of the subtree have the same value.)

Input:  root = [5,1,5,5,5,null,5]

              5
             / \
            1   5
           / \   \
          5   5   5

Output: 4






class Solution {
    int count = 0; // count must be here to be accssible from the functions below
    public int countUnivalSubtrees(TreeNode root) {
     
      helper(root);
      return count;
      
        
    }
    private boolean helper(TreeNode root){
      // base case 
      if(root == null){
        return true;
      }
      
      boolean left_result = helper(root.left);
      boolean right_result = helper(root.right);
      
      if(left_result && right_result){
        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;
    }
}

///// others code 

// dont know why use an int[] array to pass count? 
public class Solution {
    public int countUnivalSubtrees(TreeNode root) {
        int[] count = new int[1];
        helper(root, count);
        return count[0];
    }
    
    private boolean helper(TreeNode node, int[] count) {
        if (node == null) {
            return true;
        }
        boolean left = helper(node.left, count);
        boolean right = helper(node.right, count);
        if (left && right) {
            if (node.left != null && node.val != node.left.val) {
                return false;
            }
            if (node.right != null && node.val != node.right.val) {
                return false;
            }
            count[0]++;
            return true;
        }
        return false;
    }
}

 

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.

Example :

Input:  root = [5,1,5,5,5,null,5]

              5
             / \
            1   5
           / \   \
          5   5   5

Output: 4

posted on 2018-07-19 12:05  猪猪🐷  阅读(109)  评论(0)    收藏  举报

导航