There exist two undirected trees with n and m nodes, labeled from [0, n - 1] and [0, m - 1], respectively.
You are given two 2D integer arrays edges1 and edges2 of lengths n - 1 and m - 1, respectively, where edges1[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the first tree and edges2[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the second tree.
Node u is target to node v if the number of edges on the path from u to v is even. Note that a node is alwaystarget to itself.
Return an array of n integers answer, where answer[i] is the maximum possible number of nodes that are target to node i of the first tree if you had to connect one node from the first tree to another node in the second tree.
Note that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.
Input: edges1 =[[0,1],[0,2],[2,3],[2,4]], edges2 =[[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]]Output: [8,7,7,8,8]Explanation:
* For `i = 0`, connect node 0 from the first tree to node 0 from the second tree.* For `i = 1`, connect node 1 from the first tree to node 4 from the second tree.* For `i = 2`, connect node 2 from the first tree to node 7 from the second tree.* For `i = 3`, connect node 3 from the first tree to node 0 from the second tree.* For `i = 4`, connect node 4 from the first tree to node 4 from the second tree.
Input: edges1 =[[0,1],[0,2],[0,3],[0,4]], edges2 =[[0,1],[1,2],[2,3]]Output: [3,6,6,6,6]Explanation:
For every `i`, connect node `i` of the first tree with any node of the second tree.
Constraints:
2 <= n, m <= 10^5
edges1.length == n - 1
edges2.length == m - 1
edges1[i].length == edges2[i].length == 2
edges1[i] = [ai, bi]
0 <= ai, bi < n
edges2[i] = [ui, vi]
0 <= ui, vi < m
The input is generated such that edges1 and edges2 represent valid trees.
To determine the maximum number of nodes that are “target” for each node in Tree 1 after connecting it to Tree 2, the answer can be broken into two components:
Nodes in the first tree that are at an even distance from the selected node.
Nodes in the second tree that are at an even distance from the corresponding node.
The concept relies on the property that if a tree has count target nodes relative to a node u, and node v is a target of u, then v also has exactly count target nodes.
To efficiently compute the distances, we colour both trees using Depth-First Search (DFS):
Assign the root a colour of 0 (white), and every node at an even distance from the root is assigned 0 as well.
Nodes at an odd distance are assigned 1 (black).
The total count of nodes coloured 0 (white) and 1 (black) is recorded. For any node, the number of target nodes equals the count of nodes sharing its colour.
Using this, we generate two arrays, color1 for Tree 1 and color2 for Tree 2, alongside the count of white and black nodes in each tree. For the i-th query:
Look up color1[i]. The count corresponding to this colour in Tree 1 provides the first component of the result.
Since the connection structure does not affect the result, node i “interacts” with only one colour in Tree 2, and the second component is simply max(white2, black2).
classSolution {
publicint[]maxTargetNodes(int[][] edges1, int[][] edges2) {
int n = edges1.length+ 1; // Number of nodes in Tree 1int m = edges2.length+ 1; // Number of nodes in Tree 2// Colour arrays for both treesint[] color1 =newint[n];
int[] color2 =newint[m];
// Build trees and count white and black nodesint[] count1 = build(edges1, color1);
int[] count2 = build(edges2, color2);
// Compute answer for each node in Tree 1int[] res =newint[n];
for (int i = 0; i < n; i++) {
res[i]= count1[color1[i]]+ Math.max(count2[0], count2[1]);
}
return res;
}
// Build adjacency list, colour nodes, and count white and black nodesprivateint[]build(int[][] edges, int[] color) {
int n = edges.length+ 1; // Node count List<List<Integer>> children =new ArrayList<>();
for (int i = 0; i < n; i++) {
children.add(new ArrayList<>());
}
// Create adjacency listfor (int[] edge : edges) {
children.get(edge[0]).add(edge[1]);
children.get(edge[1]).add(edge[0]);
}
// Perform DFS to colour nodes and count white/blackint whiteNodes = dfs(0, -1, 0, children, color); // Start DFS at root, depth 0returnnewint[] { whiteNodes, n - whiteNodes }; // Return counts of white and black nodes }
// Depth-First Search to colour nodesprivateintdfs(int node, int parent, int depth, List<List<Integer>> children, int[] color) {
int whiteCount = 1 - (depth % 2); // Depth modulo 2 determines colour color[node]= depth % 2; // Assign node colourfor (int child : children.get(node)) {
if (child == parent) continue; // Ignore parent node whiteCount += dfs(child, node, depth + 1, children, color); // Process child }
return whiteCount;
}
}
classSolution:
defmaxTargetNodes(self, edges1: List[List[int]], edges2: List[List[int]]) -> List[int]:
n = len(edges1) +1# Number of nodes in Tree 1 m = len(edges2) +1# Number of nodes in Tree 2# Colour arrays for both trees color1 = [-1] * n
color2 = [-1] * m
# Build trees and count white/black nodes count1 = self.build(edges1, color1)
count2 = self.build(edges2, color2)
# Compute result for each node in Tree 1 res = [count1[color1[i]] + max(count2[0], count2[1]) for i in range(n)]
return res
defbuild(self, edges: List[List[int]], color: List[int]) -> List[int]:
n = len(edges) +1# Number of nodes tree = defaultdict(list)
# Create adjacency listfor a, b in edges:
tree[a].append(b)
tree[b].append(a)
# Colour nodes and count white/black using DFS whiteCount = self.dfs(0, -1, 0, color, tree) # Start DFS at rootreturn [whiteCount, n - whiteCount] # Return counts of white and black nodesdefdfs(self, node: int, parent: int, depth: int, color: List[int], tree: defaultdict) -> int:
whiteCount =1- (depth %2) # Depth modulo 2 determines colour color[node] = depth %2# Assign node colourfor child in tree[node]:
if child != parent:
whiteCount += self.dfs(child, node, depth +1, color, tree) # Process childreturn whiteCount
⏰ Time complexity: O(n + m), where n and m represent the nodes in Tree 1 and Tree 2 respectively. Tree colouring via DFS takes O(n + m) and each query is processed in O(1).
🧺 Space complexity: O(n + m). Two arrays are used to store colours, color1 for Tree 1 and color2 for Tree 2, alongside adjacency lists for both trees.