@@ -56,7 +56,13 @@ class Node {
56
56
57
57
<!-- 这里可写通用的实现逻辑 -->
58
58
59
- DFS。
59
+ ** 方法一:递归**
60
+
61
+ 我们可以用递归的方法来实现 N 叉树的深拷贝。
62
+
63
+ 对于当前节点,如果为空,则返回空;否则,创建一个新节点,其值为当前节点的值,然后对当前节点的每个子节点递归调用该函数,将返回值作为新节点的子节点。最后返回新节点即可。
64
+
65
+ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 N 叉树的节点个数。
60
66
61
67
<!-- tabs:start -->
62
68
@@ -76,10 +82,10 @@ class Node:
76
82
77
83
class Solution :
78
84
def cloneTree (self , root : ' Node' ) -> ' Node' :
79
- if root:
80
- node = Node( val = root.val)
81
- node. children = [self .cloneTree(child) for child in root.children]
82
- return node
85
+ if root is None :
86
+ return None
87
+ children = [self .cloneTree(child) for child in root.children]
88
+ return Node(root.val, children)
83
89
```
84
90
85
91
### ** Java**
@@ -115,11 +121,11 @@ class Solution {
115
121
if (root == null ) {
116
122
return null ;
117
123
}
118
- Node node = new Node (root . val );
124
+ ArrayList< Node > children = new ArrayList<> ( );
119
125
for (Node child : root. children) {
120
- node . children. add(cloneTree(child));
126
+ children. add(cloneTree(child));
121
127
}
122
- return node ;
128
+ return new Node (root . val, children) ;
123
129
}
124
130
}
125
131
```
@@ -150,16 +156,14 @@ public:
150
156
class Solution {
151
157
public:
152
158
Node* cloneTree(Node* root) {
153
- if (root == nullptr ) {
154
- return nullptr ;
159
+ if (! root) {
160
+ return root ;
155
161
}
156
- Node* node = new Node(root->val);
157
162
vector<Node* > children;
158
- for (Node* node : root->children) {
159
- children.push_back (cloneTree(node ));
163
+ for (Node* child : root->children) {
164
+ children.emplace_back (cloneTree(child ));
160
165
}
161
- node->children = children;
162
- return node;
166
+ return new Node(root->val, children);
163
167
}
164
168
};
165
169
```
@@ -179,11 +183,11 @@ func cloneTree(root *Node) *Node {
179
183
if root == nil {
180
184
return nil
181
185
}
182
- node := & Node{Val: root.Val }
186
+ children := []* Node{}
183
187
for _, child := range root.Children {
184
- node.Children = append(node.Children , cloneTree(child))
188
+ children = append(children , cloneTree(child))
185
189
}
186
- return node
190
+ return &Node{root.Val, children}
187
191
}
188
192
```
189
193
0 commit comments