Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.
Move from brute-force thinking to an efficient approach using tree strategy.
There exist two undirected trees with n and m nodes, with distinct labels in ranges [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. You are also given an integer k.
Node u is target to node v if the number of edges on the path from u to v is less than or equal to k. 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 target to node i of the first tree if you have 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.
Example 1:
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]], k = 2
Output: [9,7,9,8,8]
Explanation:
i = 0, connect node 0 from the first tree to node 0 from the second tree.i = 1, connect node 1 from the first tree to node 0 from the second tree.i = 2, connect node 2 from the first tree to node 4 from the second tree.i = 3, connect node 3 from the first tree to node 4 from the second tree.i = 4, connect node 4 from the first tree to node 4 from the second tree.Example 2:
Input: edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]], k = 1
Output: [6,3,3,3,3]
Explanation:
For every i, connect node i of the first tree with any node of the second tree.
Constraints:
2 <= n, m <= 1000edges1.length == n - 1edges2.length == m - 1edges1[i].length == edges2[i].length == 2edges1[i] = [ai, bi]0 <= ai, bi < nedges2[i] = [ui, vi]0 <= ui, vi < medges1 and edges2 represent valid trees.0 <= k <= 1000Problem summary: There exist two undirected trees with n and m nodes, with distinct labels in ranges [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. You are also given an integer k. Node u is target to node v if the number of edges on the path from u to v is less than or equal to k. 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 target to node i of the first tree if you have 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
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Tree
[[0,1],[0,2],[2,3],[2,4]] [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]] 2
[[0,1],[0,2],[0,3],[0,4]] [[0,1],[1,2],[2,3]] 1
find-minimum-diameter-after-merging-two-trees)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3372: Maximize the Number of Target Nodes After Connecting Trees I
class Solution {
public int[] maxTargetNodes(int[][] edges1, int[][] edges2, int k) {
var g2 = build(edges2);
int m = edges2.length + 1;
int t = 0;
for (int i = 0; i < m; ++i) {
t = Math.max(t, dfs(g2, i, -1, k - 1));
}
var g1 = build(edges1);
int n = edges1.length + 1;
int[] ans = new int[n];
Arrays.fill(ans, t);
for (int i = 0; i < n; ++i) {
ans[i] += dfs(g1, i, -1, k);
}
return ans;
}
private List<Integer>[] build(int[][] edges) {
int n = edges.length + 1;
List<Integer>[] g = new List[n];
Arrays.setAll(g, i -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
return g;
}
private int dfs(List<Integer>[] g, int a, int fa, int d) {
if (d < 0) {
return 0;
}
int cnt = 1;
for (int b : g[a]) {
if (b != fa) {
cnt += dfs(g, b, a, d - 1);
}
}
return cnt;
}
}
// Accepted solution for LeetCode #3372: Maximize the Number of Target Nodes After Connecting Trees I
func maxTargetNodes(edges1 [][]int, edges2 [][]int, k int) []int {
g2 := build(edges2)
m := len(edges2) + 1
t := 0
for i := 0; i < m; i++ {
t = max(t, dfs(g2, i, -1, k-1))
}
g1 := build(edges1)
n := len(edges1) + 1
ans := make([]int, n)
for i := 0; i < n; i++ {
ans[i] = t + dfs(g1, i, -1, k)
}
return ans
}
func build(edges [][]int) [][]int {
n := len(edges) + 1
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
return g
}
func dfs(g [][]int, a, fa, d int) int {
if d < 0 {
return 0
}
cnt := 1
for _, b := range g[a] {
if b != fa {
cnt += dfs(g, b, a, d-1)
}
}
return cnt
}
# Accepted solution for LeetCode #3372: Maximize the Number of Target Nodes After Connecting Trees I
class Solution:
def maxTargetNodes(
self, edges1: List[List[int]], edges2: List[List[int]], k: int
) -> List[int]:
def build(edges: List[List[int]]) -> List[List[int]]:
n = len(edges) + 1
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
return g
def dfs(g: List[List[int]], a: int, fa: int, d: int) -> int:
if d < 0:
return 0
cnt = 1
for b in g[a]:
if b != fa:
cnt += dfs(g, b, a, d - 1)
return cnt
g2 = build(edges2)
m = len(edges2) + 1
t = max(dfs(g2, i, -1, k - 1) for i in range(m))
g1 = build(edges1)
n = len(edges1) + 1
return [dfs(g1, i, -1, k) + t for i in range(n)]
// Accepted solution for LeetCode #3372: Maximize the Number of Target Nodes After Connecting Trees I
impl Solution {
pub fn max_target_nodes(edges1: Vec<Vec<i32>>, edges2: Vec<Vec<i32>>, k: i32) -> Vec<i32> {
fn build(edges: &Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let n = edges.len() + 1;
let mut g = vec![vec![]; n];
for e in edges {
let a = e[0] as usize;
let b = e[1] as usize;
g[a].push(b as i32);
g[b].push(a as i32);
}
g
}
fn dfs(g: &Vec<Vec<i32>>, a: usize, fa: i32, d: i32) -> i32 {
if d < 0 {
return 0;
}
let mut cnt = 1;
for &b in &g[a] {
if b != fa {
cnt += dfs(g, b as usize, a as i32, d - 1);
}
}
cnt
}
let g2 = build(&edges2);
let m = edges2.len() + 1;
let mut t = 0;
for i in 0..m {
t = t.max(dfs(&g2, i, -1, k - 1));
}
let g1 = build(&edges1);
let n = edges1.len() + 1;
let mut ans = vec![t; n];
for i in 0..n {
ans[i] += dfs(&g1, i, -1, k);
}
ans
}
}
// Accepted solution for LeetCode #3372: Maximize the Number of Target Nodes After Connecting Trees I
function maxTargetNodes(edges1: number[][], edges2: number[][], k: number): number[] {
const g2 = build(edges2);
const m = edges2.length + 1;
let t = 0;
for (let i = 0; i < m; i++) {
t = Math.max(t, dfs(g2, i, -1, k - 1));
}
const g1 = build(edges1);
const n = edges1.length + 1;
const ans = Array(n).fill(t);
for (let i = 0; i < n; i++) {
ans[i] += dfs(g1, i, -1, k);
}
return ans;
}
function build(edges: number[][]): number[][] {
const n = edges.length + 1;
const g: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
return g;
}
function dfs(g: number[][], a: number, fa: number, d: number): number {
if (d < 0) {
return 0;
}
let cnt = 1;
for (const b of g[a]) {
if (b !== fa) {
cnt += dfs(g, b, a, d - 1);
}
}
return cnt;
}
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.