250. Count Univalue Subtrees

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,

1
2
3
4
5
5
/ \
1 5
/ \ \
5 5 5

return 4.

解法1:

用Divide & Conquer
C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int res = 0;
public int countUnivalSubtrees(TreeNode root) {
helper(root);
return res;
}
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.left.val != root.val) {
return false;
}
if (root.right != null && root.right.val != root.val) {
return false;
}
++res;
return true;
} else {
return false;
}
}
}