File tree 1 file changed +52
-0
lines changed
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(n)
2
+ # Space: O(h)
3
+
4
+ # Definition for a Node.
5
+ class Node (object ):
6
+ def __init__ (self , val = None , children = None ):
7
+ self .val = val
8
+ self .children = children if children is not None else []
9
+
10
+
11
+ class Solution (object ):
12
+ def cloneTree (self , root ):
13
+ """
14
+ :type root: Node
15
+ :rtype: Node
16
+ """
17
+ result = [None ]
18
+ stk = [(1 , (root , result ))]
19
+ while stk :
20
+ step , params = stk .pop ()
21
+ if step == 1 :
22
+ node , ret = params
23
+ if not node :
24
+ continue
25
+ 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 = params
32
+ ret [0 ].children .append (ret1 [0 ])
33
+ return result [0 ]
34
+
35
+
36
+ # Time: O(n)
37
+ # Space: O(h)
38
+ class Solution2 (object ):
39
+ def cloneTree (self , root ):
40
+ """
41
+ :type root: Node
42
+ :rtype: Node
43
+ """
44
+ def dfs (node ):
45
+ if not node :
46
+ return None
47
+ copy = Node (node .val )
48
+ for child in node .children :
49
+ copy .children .append (dfs (child ))
50
+ return copy
51
+
52
+ return dfs (root )
You can’t perform that action at this time.
0 commit comments