您的位置:首页 > 产品设计 > UI/UE

250. Count Univalue Subtrees

2016-08-11 01:16 393 查看
道理上不是特别难,但是因为一边要返回计数一边又要返回是不是univalue所以需要一个helper函数。

public class Solution {
int cnt = 0;
public int countUnivalSubtrees(TreeNode root) {
helper(root);
return cnt;
}

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.val != root.left.val) {
return false;
}
if(root.right != null && root.val != root.right.val) {
return false;
}
cnt++;
return true;
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: