-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountUniValueSubtree.java
More file actions
58 lines (46 loc) · 1.46 KB
/
CountUniValueSubtree.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
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
public class CountUniValueSubtree {
/**
*
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
*/
public int countUnivalSubtrees(TreeNode root) {
if(root == null) return 0;
int[] res = new int[]{0};
Map<TreeNode, Boolean> map = new HashMap<>();
isUnival(root, map, res);
return res[0];
}
public boolean isUnival(TreeNode root, Map<TreeNode, Boolean> map, int[] res) {
if(root == null) return true;
if(map.get(root) != null) return map.get(root);
boolean left = isUnival(root.left, map, res);
boolean right = isUnival(root.right, map, res);
if(left && right) {
if(root.left != null && root.left.val != root.val) {
map.put(root, false);
return false;
} if(root.right != null && root.right.val != root.val) {
map.put(root, false);
return false;
} else {
res[0]++;
map.put(root, true);
return true;
}
}
return false;
}
}