Imagine you need to create an exact duplicate of a complex organizational chart or family tree structure. That's exactly what we're doing here - creating a deep copy of an N-ary tree!

Given the root of an N-ary tree, your task is to return a complete clone of the entire tree structure. Each node in the tree contains:

  • An integer value (val)
  • A list of child nodes (children)

The clone must be completely independent - modifying the original tree should not affect the cloned tree and vice versa. Think of it as creating a photocopy of a document where changes to the original don't affect the copy.

Key Challenge: Unlike binary trees which have at most 2 children, N-ary trees can have any number of children, making the cloning process more complex as we need to handle variable-length child lists.

Input & Output

example_1.py — Basic N-ary Tree
$ Input: root = [1,null,3,2,4,null,5,6]
Output: Cloned tree with same structure: [1,null,3,2,4,null,5,6]
💡 Note: The tree has root with value 1 and three children (3,2,4). Node 3 has two children (5,6). The clone maintains the exact same structure but creates completely new node objects.
example_2.py — Single Node Tree
$ Input: root = [1]
Output: Cloned single node: [1]
💡 Note: A tree with only one node (the root) is cloned to create a new node with the same value but different memory address.
example_3.py — Empty Tree
$ Input: root = null
Output: null
💡 Note: An empty tree (null root) returns null as there's nothing to clone. This is the base case for our recursive solution.

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • -1000 ≤ Node.val ≤ 1000
  • The depth of the n-ary tree is less than or equal to 1000
  • Follow up: Can you solve this problem iteratively using BFS?

Visualization

Tap to expand
Clone N-ary Tree INPUT Original N-ary Tree 1 3 2 4 5 6 Input Array: [1,null,3,2,4,null,5,6] N children per node ALGORITHM STEPS (DFS Approach) 1 Base Case Check If root is null, return null 2 Create New Node Clone current node value 3 Recursively Clone Clone all N children (DFS) 4 Return Clone Return new independent tree DFS Order: 1 3 2 4 5 6 FINAL RESULT Cloned N-ary Tree 1 3 2 4 5 6 Output Array: [1,null,3,2,4,null,5,6] OK - Deep Clone Complete Key Insight: DFS naturally handles N-ary trees by recursively cloning each child in the children list. Unlike binary trees (left/right), N-ary trees iterate through ALL children. Time: O(n), Space: O(h) where n = nodes, h = height. The clone is independent - modifications to original don't affect clone. TutorialsPoint - Clone N-ary Tree | DFS Approach
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
58.0K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen