Clone N-ary Tree — LeetCode 1490 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchHash Table
Problem
#1490
Reading time
3 min

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

MeasureComplexity
TimeO(n)
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview