Problem Description
Given a tree (an acyclic connected graph) rooted at node 0 represented by an array called parent, where parent[i] is the parent of node i (with parent[0] = -1), and a string s where s[i] represents the character assigned to node i, find the length of the longest path in the tree such that adjacent nodes on the path have different characters.
Key Insights
- The tree structure guarantees a unique path between any two nodes.
- A depth-first search (DFS) can be used to explore each subtree and aggregate the maximum valid branch lengths.
- At each node, only child paths with a different character than the current node can be extended.
- Combining the two longest valid branches stemming from a node gives the candidate longest path that passes through that node.
- A global variable is maintained to track the overall longest valid path found during traversal.
Space and Time Complexity
Time Complexity: O(n) - Each node is visited once. Space Complexity: O(n) - For recursion stack and storage of the tree structure.
Solution
We solve the problem using a DFS traversal. First, we build an adjacency list (child list) from the parent array to represent the tree. For each node, we perform a DFS that returns the length of the longest valid path starting from that node (including itself) where the adjacent characters differ. For every node, we consider all its children and update the two longest valid branch lengths only if their characters differ from the current node. The candidate longest path passing through a node is the sum of the two longest valid branch lengths plus 1 (for the current node). We update a global maximum with this value at every node. Finally, the DFS returns the overall maximum path length.