- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountUniValueSubtree.java
More file actions
Latest commit
58 lines (46 loc) · 1.46 KB
/
Copy pathCountUniValueSubtree.java
File metadata and controls
58 lines (46 loc) · 1.46 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
importjava.util.HashMap;
importjava.util.LinkedList;
importjava.util.Map;
importjava.util.Queue;
publicclassCountUniValueSubtree {
/**
*
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.
Example :
Input: root = [5,1,5,5,5,null,5]
5
/ \
1 5
/ \ \
5 5 5
Output: 4
*/
publicintcountUnivalSubtrees(TreeNoderoot) {
if(root == null) return0;
int[] res = newint[]{0};
Map<TreeNode, Boolean> map = newHashMap<>();
isUnival(root, map, res);
returnres[0];
}
publicbooleanisUnival(TreeNoderoot, Map<TreeNode, Boolean> map, int[] res) {
if(root == null) returntrue;
if(map.get(root) != null) returnmap.get(root);
booleanleft = isUnival(root.left, map, res);
booleanright = isUnival(root.right, map, res);
if(left && right) {
if(root.left != null && root.left.val != root.val) {
map.put(root, false);
returnfalse;
} if(root.right != null && root.right.val != root.val) {
map.put(root, false);
returnfalse;
} else {
res[0]++;
map.put(root, true);
returntrue;
}
}
returnfalse;
}
}