File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change @@ -426,6 +426,46 @@ func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
426
426
root1.Right = mergeTrees (root1.Right , root2.Right )
427
427
return root1
428
428
}
429
+
430
+ // 迭代版本
431
+ func mergeTrees (root1 *TreeNode , root2 *TreeNode ) *TreeNode {
432
+ queue := make ([]*TreeNode,0 )
433
+ if root1 == nil {
434
+ return root2
435
+ }
436
+ if root2 == nil {
437
+ return root1
438
+ }
439
+ queue = append (queue,root1)
440
+ queue = append (queue,root2)
441
+
442
+ for size := len (queue);size>0 ;size=len (queue){
443
+ node1 := queue[0 ]
444
+ queue = queue[1 :]
445
+ node2 := queue[0 ]
446
+ queue = queue[1 :]
447
+ node1.Val += node2.Val
448
+ // 左子树都不为空
449
+ if node1.Left != nil && node2.Left != nil {
450
+ queue = append (queue,node1.Left )
451
+ queue = append (queue,node2.Left )
452
+ }
453
+ // 右子树都不为空
454
+ if node1.Right !=nil && node2.Right !=nil {
455
+ queue = append (queue,node1.Right )
456
+ queue = append (queue,node2.Right )
457
+ }
458
+ // 树 1 的左子树为 nil,直接接上树 2 的左子树
459
+ if node1.Left == nil {
460
+ node1.Left = node2.Left
461
+ }
462
+ // 树 1 的右子树为 nil,直接接上树 2 的右子树
463
+ if node1.Right == nil {
464
+ node1.Right = node2.Right
465
+ }
466
+ }
467
+ return root1
468
+ }
429
469
```
430
470
431
471
JavaScript:
You can’t perform that action at this time.
0 commit comments