Problem

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 always target 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.

Examples

Example 1:

graph LR

    subgraph Tree1["Tree 1"]
		A(0) --- B(1)
		A(0) --- C(2)
		C(2) --- D(3)
		C(2) --- E(4)
    end
    
    subgraph Tree2["Tree 2"]
		A2(0) --- B2(1)
		A2(0) --- C2(2)
		A2(0) --- D2(3)
		C2(2) --- G2(7)
		B2(1) --- E2(4)
		E2(4) --- F2(5)
		E2(4) --- H2(6)
    end
    
    
	Tree1 ~~~ Tree2
  
1
2
3
4
5
6
7
8
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.

Example 2:

 graph LR
 
     subgraph Tree1["Tree 1"]
 		A(0) --- B(1)
 		A(0) --- C(2)
 		A(0) --- D(3)
 		A(0) --- E(4)
     end
     
     subgraph Tree2["Tree 2"]
 		A2(0) --- B2(1)
 		B2(1) --- C2(2)
 		C2(2) --- D2(3)
     end
     
     
 	Tree1 ~~~ Tree2
  
1
2
3
4
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.

Solution

Method 1 - Using DFS

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:

  1. Nodes in the first tree that are at an even distance from the selected node.
  2. 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).

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {

    public int[] maxTargetNodes(int[][] edges1, int[][] edges2) {
        int n = edges1.length + 1; // Number of nodes in Tree 1
        int m = edges2.length + 1; // Number of nodes in Tree 2
        
        // Colour arrays for both trees
        int[] color1 = new int[n];
        int[] color2 = new int[m];
        
        // Build trees and count white and black nodes
        int[] count1 = build(edges1, color1);
        int[] count2 = build(edges2, color2);
        
        // Compute answer for each node in Tree 1
        int[] res = new int[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 nodes
    private int[] 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 list
        for (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/black
        int whiteNodes = dfs(0, -1, 0, children, color); // Start DFS at root, depth 0
        return new int[] { whiteNodes, n - whiteNodes }; // Return counts of white and black nodes
    }

    // Depth-First Search to colour nodes
    private int dfs(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 colour
        for (int child : children.get(node)) {
            if (child == parent) continue; // Ignore parent node
            whiteCount += dfs(child, node, depth + 1, children, color); // Process child
        }
        return whiteCount;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution:
    def maxTargetNodes(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

    def build(self, edges: List[List[int]], color: List[int]) -> List[int]:
        n = len(edges) + 1  # Number of nodes
        tree = defaultdict(list)
        
        # Create adjacency list
        for 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 root
        return [whiteCount, n - whiteCount]  # Return counts of white and black nodes

    def dfs(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 colour
        for child in tree[node]:
            if child != parent:
                whiteCount += self.dfs(child, node, depth + 1, color, tree)  # Process child
        return whiteCount

Complexity

  • ⏰ 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.