NeetCode #409LC-1490MediumTreesNC Algo100
← Back to All Problems#409 · #1490 · Clone N-ary Tree(克隆 N 叉树)
📌 Problem Statement & Constraints
You are given a reference to an N-ary tree. Return a deep copy of the tree. Constraints: the number of nodes is in
[0, 10^4], 0 <= Node.val <= 10^4, the tree depth is at most 1000.💡 Core Algorithmic Approaches
- A recursive clone is the natural fit: copy the node's value, then recursively clone each child.
- The key point is that the copy must be deep -- sharing child references would alias the original structure.
- The
Nonebase case returnsNone. - An iterative version uses a stack of
(original, copy)pairs.
💻 Benchmark Python3 Implementation
class Solution:
def cloneTree(self, root: "Optional[Node]") -> "Optional[Node]":
if not root:
return None
node = Node(root.val) # shallow copy of the value
node.children = [self.cloneTree(c) for c in root.children] # deep copy
return node⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each node is copied once.
💾 Space Complexity
O(h) for the recursion stack, where h is the tree depth.
⚠️ Interview Pitfalls & Follow-ups
- Sharing the children list:
node.children = root.childrenaliases the original; the list and every node in it must be copied. - Using
copy.copy: a shallow copy still shares the children. - Forgetting the empty-tree case:
Nonemust be handled before accessing.val. - Recursing on a very deep tree: the depth can reach 1000, which is within Python's default limit but close.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Trees Problems
中文速览与面试要点
克隆 N 叉树
给定一棵 N 叉树的根节点 root,返回该树的 深拷贝 (克隆)。N 叉树的每个节点包含一个节点值和一个子节点列表。约束:树的节点数在范围 [0, 10^4] 内;0 ≤ Node.val ≤ 10^4;树的高度不超过 1000。
核心要点
- 递归深拷贝(标准解) :创建新节点,然后递归克隆每个子节点并加入 children 列表。
- 为什么必须深拷贝 :题目要求返回全新的树,节点与子节点列表都不能与原树共享引用。
- 若树中有环或重复引用 :需要哈希表 原节点 → 新节点 做记忆化(本题是无环树,不需要)。
- 复杂度 :O(n) 时间、O(h) 空间(递归栈)。
常见陷阱
- 直接赋值 node.children = root.children :那是浅拷贝,两个树会共享子节点列表。
- 忘记初始化 children 为空列表 : Node(root.val) 通常已默认空列表,但若实现不同需显式处理。
- 递归深度过大 :树高可达 1000,递归深度 1000 接近 Python 默认上限,必要时改迭代。
参考实现
class Solution:
def cloneTree(self, root: 'Node') -> 'Node':
if not root:
return None
node = Node(root.val) # 新建节点(children 默认为空列表)
node.children = [self.cloneTree(c) for c in root.children]
return node