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,
return
递归解题。如果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;
}
}
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;
}
}
相关文章推荐
- 250. Count Univalue Subtrees
- [Leetcode] 250. Count Univalue Subtrees 解题报告
- [leetcode] 250. Count Univalue Subtrees 解题报告
- 250. Count Univalue Subtrees
- LeetCode 250. Count Univalue Subtrees(单值子树)
- 250. Count Univalue Subtrees
- Leetcode 250. Count Univalue Subtrees (Medium) (cpp)
- [LeetCode] 250. Count Univalue Subtrees 计算唯一值子树的个数
- LeetCode 250. Count Univalue Subtrees
- 250. Count Univalue Subtrees
- 250. Count Univalue Subtrees
- Leetcode: Count Univalue Subtrees
- *Count Univalue Subtrees
- Leetcode 250 Count Univalue Subtrees
- Count Univalue Subtrees
- LeetCode Count Univalue Subtrees
- LeetCode-Count Univalue Subtrees
- [LeetCode] Count Univalue Subtrees 计数相同值子树的个数
- [Locked] Count Univalue Subtrees
- [leetcode 250]Count Univalue Subtrees ------元素都相同的子树个数