File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -256,7 +256,60 @@ public:
256
256
257
257
258
258
Java:
259
+ ```Java
260
+ class Solution {
261
+ // 递归
262
+ public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
263
+ if (root1 == null) {
264
+ return root2;
265
+ }
266
+ if (root2 == null) {
267
+ return root1;
268
+ }
269
+ root1.val += root2.val;
270
+ root1.left = mergeTrees(root1.left, root2.left);
271
+ root1.right = mergeTrees(root1.right, root2.right);
272
+ return root1;
273
+ }
274
+ }
259
275
276
+ class Solution {
277
+ // 迭代
278
+ public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
279
+ if (root1 == null) {
280
+ return root2;
281
+ }
282
+ if (root2 == null) {
283
+ return root1;
284
+ }
285
+ Stack<TreeNode> stack = new Stack<>();
286
+ stack.push(root2);
287
+ stack.push(root1);
288
+ while (!stack.isEmpty()) {
289
+ TreeNode node1 = stack.pop();
290
+ TreeNode node2 = stack.pop();
291
+ node1.val += node2.val;
292
+ if (node2.right != null && node1.right != null) {
293
+ stack.push(node2.right);
294
+ stack.push(node1.right);
295
+ } else {
296
+ if (node1.right == null) {
297
+ node1.right = node2.right;
298
+ }
299
+ }
300
+ if (node2.left != null && node1.left != null) {
301
+ stack.push(node2.left);
302
+ stack.push(node1.left);
303
+ } else {
304
+ if (node1.left == null) {
305
+ node1.left = node2.left;
306
+ }
307
+ }
308
+ }
309
+ return root1;
310
+ }
311
+ }
312
+ ```
260
313
261
314
Python:
262
315
You can’t perform that action at this time.
0 commit comments