Loading content...
You are given the root of an N-ary tree structure, where each node contains an integer value and can have an arbitrary number of child nodes. Your task is to create and return a complete independent replica of this tree.
A complete independent replica (also known as a deep copy) means that every node in the new tree must be a freshly allocated object in memory. The replica must preserve the exact same structure and values as the original tree, but no node in the replica should share memory references with any node in the original tree. Modifying the replica should have no effect on the original tree, and vice versa.
Each node in the N-ary tree is defined with the following structure:
class Node {
public int val;
public List<Node> children;
}
Where val is an integer representing the node's value, and children is a list containing references to all the node's child nodes (which can be empty if the node is a leaf).
N-ary Tree Serialization Format:
The N-ary tree input is serialized using level-order traversal. Each group of children is separated by a null value to indicate the boundary between different parent nodes. For example, the serialization [1,null,3,2,4,null,5,6] represents a tree where node 1 is the root with children 3, 2, and 4, and node 3 has children 5 and 6.
root = [1,null,3,2,4,null,5,6][1,null,3,2,4,null,5,6]The tree has root value 1 with three children (3, 2, 4). Node 3 has two children (5, 6), while nodes 2 and 4 are leaf nodes. The replica preserves this exact structure with all new node objects.
root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,null,null,14][1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,null,null,14]A more complex N-ary tree with multiple levels and varying numbers of children per node. The deep copy replicates the entire hierarchical structure faithfully.
root = [42][42]A single-node tree where the root has no children. The replica is simply a new node with value 42 and an empty children list.
Constraints