Approach
Depth-first search
For Clone N Ary Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 53 lines of Python from the credited upstream file clone-n-ary-tree.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Node(object):6 def __init__(self, val=None, children=None):7 self.val = val8 self.children = children if children is not None else []9 10 11class Solution(object):12 def cloneTree(self, root):13 """14 :type root: Node15 :rtype: Node16 """17 result = [None]18 stk = [(1, (root, result))]19 while stk:20 step, params = stk.pop()21 if step == 1:22 node, ret = params23 if not node:24 continue25 ret[0] = Node(node.val)26 for child in reversed(node.children):27 ret1 = [None]28 stk.append((2, (ret1, ret)))29 stk.append((1, (child, ret1)))30 else:31 ret1, ret = params32 ret[0].children.append(ret1[0])33 return result[0]34 35 363738class Solution2(object):39 def cloneTree(self, root):40 """41 :type root: Node42 :rtype: Node43 """44 def dfs(node):45 if not node:46 return None47 copy = Node(node.val)48 for child in node.children:49 copy.children.append(dfs(child))50 return copy51 52 return dfs(root)53