- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_3004.java
81 lines (74 loc) · 2.96 KB
/
_3004.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
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
packagecom.fishercoder.solutions.fourththousand;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
publicclass_3004 {
publicstaticclassSolution1 {
/*
* My completely original solution.
* Practice makes perfect!
* Post-order traversal is the way to go since we need to process all children first before processing any particular node.
*/
classColoredTreeNode {
intval;
intcolor;
List<ColoredTreeNode> children;
booleanallSubtreeSameColor;
inttotalChildrenCount;
publicColoredTreeNode(intval, intcolor) {
this.val = val;
this.color = color;
this.children = newArrayList<>();
this.allSubtreeSameColor =
true; // initialize to be true until it's built/proven to be false
this.totalChildrenCount = 1; // count itself as its own child
}
}
intmaxSize = 0;
publicintmaximumSubtreeSize(int[][] edges, int[] colors) {
if (edges == null || edges.length == 0 || edges[0].length == 0) {
returncolors.length > 0 ? 1 : 0;
}
ColoredTreeNoderoot = buildTree(edges, colors);
inttotalNodeCount = postOrder(root);
if (root.allSubtreeSameColor) {
returntotalNodeCount;
}
returnmaxSize;
}
privateintpostOrder(ColoredTreeNoderoot) {
if (root == null) {
return0;
}
inttotalChildrenCount = 1; // count itself as a child
for (ColoredTreeNodechild : root.children) {
intcount = postOrder(child);
totalChildrenCount += count;
if (root.color != child.color || !child.allSubtreeSameColor) {
root.allSubtreeSameColor = false;
}
}
root.totalChildrenCount = totalChildrenCount;
if (root.allSubtreeSameColor) {
maxSize = Math.max(maxSize, root.totalChildrenCount);
}
returntotalChildrenCount;
}
privateColoredTreeNodebuildTree(int[][] edges, int[] colors) {
Map<Integer, ColoredTreeNode> map = newHashMap<>();
for (inti = 0; i < edges.length; i++) {
ColoredTreeNodeparent =
map.getOrDefault(
edges[i][0], newColoredTreeNode(edges[i][0], colors[edges[i][0]]));
ColoredTreeNodechild =
map.getOrDefault(
edges[i][1], newColoredTreeNode(edges[i][1], colors[edges[i][1]]));
parent.children.add(child);
map.put(edges[i][0], parent);
map.put(edges[i][1], child);
}
returnmap.get(0);
}
}
}