#1490
Medium Algorithms Clone n ary tree
Hash Table Tree Depth-First Search Breadth-First Search
83.1% acceptance
Mar 31, 2026
427
17
Given a root of an N-ary tree, return a deep copy (clone) of the tree.
Each node in the n-ary tree contains a val (int) and a list (List[Node]) of its children.
class Node {
public int val;
public List children;
}
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Solution
C++
Time O(n)
Space O(1)
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
Node* cloneTree(Node* root) {
if (!root) return nullptr;
Node* clone = new Node(root->val);
for (auto* child : root->children) {
clone->children.push_back(cloneTree(child));
}
return clone;
}
};