MediumNo. 1490LeetCode Premium
Clone N-ary Tree — LeetCode 1490 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Breadth-First Search, Hash Table
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
class Node {
public int val;
public List<Node> children;
}Python solution
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
"""
class Solution:
def cloneTree(self, root: 'Node') -> 'Node':
if root is None:
return None
children = [self.cloneTree(child) for child in root.children]
return Node(root.val, children)Complexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1490. Clone N-ary Tree is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0653 | Two Sum IV - Input is a BST | Easy |
| 0690 | Employee Importance | Medium |
| 0863 | All Nodes Distance K in Binary Tree | Medium |
| 0865 | Smallest Subtree with all the Deepest Nodes | Medium |
| 0987 | Vertical Order Traversal of a Binary Tree | Hard |
| 1123 | Lowest Common Ancestor of Deepest Leaves | Medium |
Frequently asked questions
- How hard is LeetCode 1490. Clone N-ary Tree?
LeetCode 1490. Clone N-ary Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1490. Clone N-ary Tree?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1490. Clone N-ary Tree?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1490. Clone N-ary Tree cover?
LeetCode 1490. Clone N-ary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Hash Table on LeetCode.
- Is LeetCode 1490. Clone N-ary Tree a premium problem?
Yes. LeetCode 1490. Clone N-ary Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.