This is a harder variation of connecting two trees. You are given two trees. You can add one edge connecting any node from Tree 1 to any node from Tree 2. You need to return an array for Tree 1, where the -th element is the maximum number of target nodes reachable from node . In this version, a node is a "target node" if the path from node to that node has an even number of edges.
This problem introduces Bipartite Graphs / Tree Coloring. Because the target condition relies on "even path lengths", it elegantly tests a candidate's understanding of graph parity. Interviewers use it to see if you can recognize that any tree is inherently bipartite, and that nodes can be painted in two alternating colors (e.g., Red and Blue) to instantly solve even/odd distance queries in time.
This problem leverages Tree Bipartition (2-Coloring).
max_tree2_even.i in Tree 1 will reach all nodes in Tree 1 that share the same color as node i.i to Tree 2, the edge itself adds 1 to the path length. To hit nodes in Tree 2 with an even path, we want the connection to act as an alternating bridge. We simply add max_tree2_even to our count.i = (Count of nodes in Tree 1 with same color as i) + max_tree2_even.Tree 1: A - B - C.
Coloring: A (Red), B (Blue), C (Red).
Tree 1 totals: 2 Red, 1 Blue.
Tree 2: X - Y.
Coloring: X (Red), Y (Blue).
Tree 2 totals: 1 Red, 1 Blue. Max even reach in Tree 2 is 1.
Query for node A (Red):
max_tree2_even (1).Query for node B (Blue):
Candidates who don't recognize the bipartite nature of trees will attempt to run BFS from every node to count path lengths, resulting in time. The realization that "even distance" simply means "same parity level" or "same color in a bipartite graph" is crucial. Another mistake is forgetting that connecting the edge shifts the parity for Tree 2, but since we just take the max(color1, color2) of Tree 2, it handles itself perfectly.
When tackling graph problems involving "even" or "odd" edge distances, immediately think of Graph Coloring (Bipartite graphs). In a tree, the unique path between two nodes of the same color always has an even length, and between different colors always has an odd length. This property reduces complex distance traversals into simple integer counting.