forked from szl0072/Leetcode-Solution-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountUnivalueSubtrees.java
More file actions
63 lines (51 loc) · 1.25 KB
/
CountUnivalueSubtrees.java
File metadata and controls
63 lines (51 loc) · 1.25 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package leetcode;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : CountUnivalueSubtrees
* Creator : Edward
* Date : Nov, 2017
* Description : 250. Count Univalue Subtrees
*/
public class CountUnivalueSubtrees {
/**
* 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 = 5 res = 2
root = 1
root = 5 res = 3
root = 5 res = 4
time : O(n)
space : O(n)
*/
int res;
public int countUnivalSubtrees(TreeNode root) {
res = 0;
helper(root);
return res;
}
public 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;
}
res++;
return true;
}
return false;
}
}