|
| 1 | +package com.fishercoder.solutions.fourththousand; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +public class _3004 { |
| 9 | + public static class Solution1 { |
| 10 | + /** |
| 11 | + * My completely original solution. |
| 12 | + * Practice makes perfect! |
| 13 | + * Post-order traversal is the way to go since we need to process all children first before processing any particular node. |
| 14 | + */ |
| 15 | + class ColoredTreeNode { |
| 16 | + int val; |
| 17 | + int color; |
| 18 | + List<ColoredTreeNode> children; |
| 19 | + boolean allSubtreeSameColor; |
| 20 | + int totalChildrenCount; |
| 21 | + |
| 22 | + public ColoredTreeNode(int val, int color) { |
| 23 | + this.val = val; |
| 24 | + this.color = color; |
| 25 | + this.children = new ArrayList<>(); |
| 26 | + this.allSubtreeSameColor = true;//initialize to be true until it's built/proven to be false |
| 27 | + this.totalChildrenCount = 1;//count itself as its own child |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + int maxSize = 0; |
| 32 | + |
| 33 | + public int maximumSubtreeSize(int[][] edges, int[] colors) { |
| 34 | + if (edges == null || edges.length == 0 || edges[0].length == 0) { |
| 35 | + return colors.length > 0 ? 1 : 0; |
| 36 | + } |
| 37 | + ColoredTreeNode root = buildTree(edges, colors); |
| 38 | + int totalNodeCount = postOrder(root); |
| 39 | + if (root.allSubtreeSameColor) { |
| 40 | + return totalNodeCount; |
| 41 | + } |
| 42 | + return maxSize; |
| 43 | + } |
| 44 | + |
| 45 | + private int postOrder(ColoredTreeNode root) { |
| 46 | + if (root == null) { |
| 47 | + return 0; |
| 48 | + } |
| 49 | + int totalChildrenCount = 1;//count itself as a child |
| 50 | + for (ColoredTreeNode child : root.children) { |
| 51 | + int count = postOrder(child); |
| 52 | + totalChildrenCount += count; |
| 53 | + if (root.color != child.color || !child.allSubtreeSameColor) { |
| 54 | + root.allSubtreeSameColor = false; |
| 55 | + } |
| 56 | + } |
| 57 | + root.totalChildrenCount = totalChildrenCount; |
| 58 | + if (root.allSubtreeSameColor) { |
| 59 | + maxSize = Math.max(maxSize, root.totalChildrenCount); |
| 60 | + } |
| 61 | + return totalChildrenCount; |
| 62 | + } |
| 63 | + |
| 64 | + private ColoredTreeNode buildTree(int[][] edges, int[] colors) { |
| 65 | + Map<Integer, ColoredTreeNode> map = new HashMap<>(); |
| 66 | + for (int i = 0; i < edges.length; i++) { |
| 67 | + ColoredTreeNode parent = map.getOrDefault(edges[i][0], new ColoredTreeNode(edges[i][0], colors[edges[i][0]])); |
| 68 | + ColoredTreeNode child = map.getOrDefault(edges[i][1], new ColoredTreeNode(edges[i][1], colors[edges[i][1]])); |
| 69 | + parent.children.add(child); |
| 70 | + map.put(edges[i][0], parent); |
| 71 | + map.put(edges[i][1], child); |
| 72 | + } |
| 73 | + return map.get(0); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments