首页 > 其他 > 详细

250. Count Univalue Subtrees

时间:2018-07-19 13:12:09      阅读:159      评论:0      收藏:0      [点我收藏+]
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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!