Skip to content

Commit

Permalink
Update 0617.合并二叉树.md
Browse files Browse the repository at this point in the history
修改逻辑与题解相同.
  • Loading branch information
KelvinG-LGTM committed Aug 1, 2021
1 parent 6bbfebd commit 932d277
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions problems/0617.合并二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -312,23 +312,34 @@ class Solution {
```

Python:

**递归法 - 前序遍历**
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# 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
if not root2: return root1 // 如果t2为空,合并之后就应该是t1
root1.val = root1.val + root2.val //
root1.left = self.mergeTrees(root1.left , root2.left) //
root1.right = self.mergeTrees(root1.right , root2.right) //
return root1 //root1修改了结构和数值
# 递归终止条件:
# 但凡有一个节点为空, 就立刻返回另外一个. 如果另外一个也为None就直接返回None.
if not root1:
return root2
if not root2:
return root1
# 上面的递归终止条件保证了代码执行到这里root1, root2都非空.
root1.val += root2.val #
root1.left = self.mergeTrees(root1.left, root2.left) #
root1.right = self.mergeTrees(root1.right, root2.right) #

return root1 # ⚠️ 注意: 本题我们重复使用了题目给出的节点而不是创建新节点. 节省时间, 空间.

```

**迭代法**
```python
# 迭代法-覆盖原来的树
class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
Expand Down

0 comments on commit 932d277

Please sign in to comment.