Clone N-ary Tree — LeetCode 1490 Python Solution
MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchHash Table
- Problem
- #1490
- Pattern
- Tree Traversal
- 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
Python
"""
# 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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
LeetCode 653Two Sum IV - Input is a BSTEasyLeetCode 690Employee ImportanceMediumLeetCode 863All Nodes Distance K in Binary TreeMediumLeetCode 865Smallest Subtree with all the Deepest NodesMediumLeetCode 987Vertical Order Traversal of a Binary TreeHardLeetCode 1123Lowest Common Ancestor of Deepest LeavesMedium
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.