652. Clone N-ary Tree

Given the root of an N-ary tree, return a deep copy (clone) of the tree.

An N-ary tree is a tree in which each node has at most N children. Each node is defined by a Node class, which contains:

  • An integer val, representing the node's value.
  • A list children, containing the node's child nodes.

The deep copy should have the same structure and values as the original tree, but all nodes should be newly created (i.e., no references to the original tree should exist in the copy).

Example 1:

Input: root = [1,null,3,2,4,null,5,6]

Output: [1,null,3,2,4,null,5,6]

Example 2:

Input: 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,14]

Output: [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]

Now Your Turn!

Pick the correct output for the given input

Input: root = [1,null,2,3,4,5,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The depth of the n-ary tree is less than or equal to 1000.
  • The total number of nodes is between [0, 10⁴].

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for an n-ary tree node.
* class TreeNode {
* public:
* int val;
* vector<TreeNode*> children;
*
* TreeNode() {}
*
* TreeNode(int _val) {
* val = _val;
* }
*
* TreeNode(int _val, vector<TreeNode*> _children) {
* val = _val;
* children = _children;
* }
* };
**/
 
class Solution {
public:
TreeNode* cloneTree(TreeNode* root) {
}
};
Test Case

Input:

Root