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

250. Count Univalue Subtrees

2017-05-31 07:56 316 查看
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.

For example:

Given binary tree,

5
/ \
1   5
/ \   \
5   5   5


return 
4
.
递归解题。如果root == null,返回true。如果左右都是true,而且root.val == root.left.val,root.val == root.right.val,count ++返回true,否则返回false。代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int count;

public int countUnivalSubtrees(TreeNode root) {
count = 0;
helper(root);
return count;
}

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;
}
count ++;
return true;
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: