首页 > 其他 > 详细

250. Count Univalue Subtrees

时间:2016-08-11 06:16:33      阅读:101      评论:0      收藏:0      [点我收藏+]

道理上不是特别难,但是因为一边要返回计数一边又要返回是不是univalue所以需要一个helper函数。

 1 public class Solution {
 2     int cnt = 0;
 3     public int countUnivalSubtrees(TreeNode root) {
 4         helper(root);
 5         return cnt;
 6     }
 7     
 8     private boolean helper(TreeNode root) {
 9         if(root == null) {
10             return true;
11         }
12         boolean left = helper(root.left);
13         boolean right = helper(root.right);
14         if(left && right) {
15             if(root.left != null && root.val != root.left.val) {
16                 return false;
17             }
18             if(root.right != null && root.val != root.right.val) {
19                 return false;
20             }
21             cnt++;
22             return true;
23         }
24         return false;
25     }
26 }

 

250. Count Univalue Subtrees

原文:http://www.cnblogs.com/warmland/p/5759456.html

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