Problem Description
Given a tree (an acyclic connected graph) with n nodes (numbered from 0 to n-1) represented by a list of edges, and an array colors where colors[i] denotes the color of node i, find a node v such that every node in the subtree of v has the same color. Return the maximum number of nodes among these subtrees.
Key Insights
- The tree is processed using Depth-First Search (DFS) since each node’s property (whether its subtree is homogeneous) depends on the properties of its children.
- For a node to have a homogeneous subtree, every one of its children must have a homogeneous subtree with the same color as the parent.
- A global variable can be maintained to keep track of the maximum subtree size encountered that is homogeneous.
- Use an adjacency list to represent the tree given the edge list.
Space and Time Complexity
Time Complexity: O(n) – Each node is visited exactly once. Space Complexity: O(n) – The recursion stack and the adjacency list can both take O(n) space.
Solution
We approach the problem with a recursive DFS. We first build an adjacency list from the given edge list. Then for each node during the DFS, we check whether all its children have a homogeneous subtree that shares the same color as the node itself. If so, the size of the subtree rooted at that node will be 1 (for the node itself) plus the sizes of all the homogeneous subtrees of its children. Otherwise, that node does not qualify as having a homogeneous subtree (and we denote this by returning a marker value such as -1). At every node that qualifies, we update a global maximum subtree size variable. This ensures that by the end of DFS, we have the size of the largest subtree where every node has the same color.