Merge two N-ary trees by key rules

Quick Overview

This question evaluates understanding of N-ary tree data structures, hierarchical merging semantics, and algorithmic reasoning about recursion and key-based child reconciliation.

Merge two N-ary trees by key rules

Company: LinkedIn

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Onsite

You are given two **N-ary trees** `A` and `B`. Each node has: - `key` (string): unique among siblings (i.e., within a node’s children list, no two children share the same key) - `value` (any scalar, e.g., string/int) - `children` (list of nodes) You must produce a merged tree `M = merge(A, B)` using these rules: ## Merge rules 1. **If a node exists in both trees at the same position (matched by `key`)**: - The merged node’s `key` stays the same. - The merged node’s `value` is **taken from tree `B`** (i.e., `B` overwrites `A`). - The merged node’s `children` are formed by merging children lists by key, recursively. 2. **If a child key exists only in one tree**: - Include that subtree unchanged in the output. Assume the two input roots have the **same key**. ## Task Implement a function to merge the two trees and return the merged root. ## Constraints - Total nodes across both trees: up to `2 * 10^5` - Keys are non-empty strings ## Clarifications - Sibling order in the output does not matter unless you choose to preserve a stable order.

Quick Answer: This question evaluates understanding of N-ary tree data structures, hierarchical merging semantics, and algorithmic reasoning about recursion and key-based child reconciliation.

|Home/Coding & Algorithms/LinkedIn
LinkedIn logo
LinkedIn
Nov 21, 2025, 12:00 AM
mediumSoftware EngineerOnsiteCoding & Algorithms
43
0

You are given two N-ary trees A and B. Each node has:

  • key (string): unique among siblings (i.e., within a node’s children list, no two children share the same key)
  • value (any scalar, e.g., string/int)
  • children (list of nodes)

You must produce a merged tree M = merge(A, B) using these rules:

Merge rules

  1. If a node exists in both trees at the same position (matched by key) :
    • The merged node’s key stays the same.
    • The merged node’s value is taken from tree B (i.e., B overwrites A ).
    • The merged node’s children are formed by merging children lists by key, recursively.
  2. If a child key exists only in one tree :
    • Include that subtree unchanged in the output.

Assume the two input roots have the same key.

Task

Implement a function to merge the two trees and return the merged root.

Constraints

  • Total nodes across both trees: up to 2 * 10^5
  • Keys are non-empty strings

Clarifications

  • Sibling order in the output does not matter unless you choose to preserve a stable order.

Submit Your Answer to Earn 20XP

Sign in to leave a comment

Loading comments...