diff --git a/problems/0617.合并二叉树.md b/problems/0617.合并二叉树.md index f325df64..19b58bd3 100644 --- a/problems/0617.合并二叉树.md +++ b/problems/0617.合并二叉树.md @@ -319,7 +319,7 @@ Python: # self.val = val # self.left = left # self.right = right -//递归法*前序遍历 +# 递归法*前序遍历 class Solution: def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: if not root1: return root2 // 如果t1为空,合并之后就应该是t2 @@ -328,6 +328,32 @@ class Solution: root1.left = self.mergeTrees(root1.left , root2.left) //左 root1.right = self.mergeTrees(root1.right , root2.right) //右 return root1 //root1修改了结构和数值 + +# 迭代法-覆盖原来的树 +class Solution: + def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: + if not root1: return root2 + if not root2: return root1 + # 迭代,将树2覆盖到树1 + queue1 = [root1] + queue2 = [root2] + root = root1 + while queue1 and queue2: + root1 = queue1.pop(0) + root2 = queue2.pop(0) + root1.val += root2.val + if not root1.left: # 如果树1左儿子不存在,则覆盖后树1的左儿子为树2的左儿子 + root1.left = root2.left + elif root1.left and root2.left: + queue1.append(root1.left) + queue2.append(root2.left) + + if not root1.right: # 同理,处理右儿子 + root1.right = root2.right + elif root1.right and root2.right: + queue1.append(root1.right) + queue2.append(root2.right) + return root ``` Go: