码迷,mamicode.com
首页 > 其他好文 > 详细

250. Count Univalue Subtrees

时间:2018-07-19 13:39:54      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:cas   nod   tree   root   return   from   rom   HERE   array   

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;
    }
}

 

250. Count Univalue Subtrees

标签:cas   nod   tree   root   return   from   rom   HERE   array   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9335053.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!