File tree Expand file tree Collapse file tree 1 file changed +18
-7
lines changed Expand file tree Collapse file tree 1 file changed +18
-7
lines changed Original file line number Diff line number Diff line change @@ -312,23 +312,34 @@ class Solution {
312
312
```
313
313
314
314
Python:
315
+
316
+ ** 递归法 - 前序遍历**
315
317
``` python
316
318
# Definition for a binary tree node.
317
319
# class TreeNode:
318
320
# def __init__(self, val=0, left=None, right=None):
319
321
# self.val = val
320
322
# self.left = left
321
323
# self.right = right
322
- # 递归法*前序遍历
323
324
class Solution :
324
325
def mergeTrees (self , root1 : TreeNode, root2 : TreeNode) -> TreeNode:
325
- if not root1: return root2 // 如果t1为空,合并之后就应该是t2
326
- if not root2: return root1 // 如果t2为空,合并之后就应该是t1
327
- root1.val = root1.val + root2.val // 中
328
- root1.left = self .mergeTrees(root1.left , root2.left) // 左
329
- root1.right = self .mergeTrees(root1.right , root2.right) // 右
330
- return root1 // root1修改了结构和数值
326
+ # 递归终止条件:
327
+ # 但凡有一个节点为空, 就立刻返回另外一个. 如果另外一个也为None就直接返回None.
328
+ if not root1:
329
+ return root2
330
+ if not root2:
331
+ return root1
332
+ # 上面的递归终止条件保证了代码执行到这里root1, root2都非空.
333
+ root1.val += root2.val # 中
334
+ root1.left = self .mergeTrees(root1.left, root2.left) # 左
335
+ root1.right = self .mergeTrees(root1.right, root2.right) # 右
336
+
337
+ return root1 # ⚠️ 注意: 本题我们重复使用了题目给出的节点而不是创建新节点. 节省时间, 空间.
331
338
339
+ ```
340
+
341
+ ** 迭代法**
342
+ ``` python
332
343
# 迭代法-覆盖原来的树
333
344
class Solution :
334
345
def mergeTrees (self , root1 : TreeNode, root2 : TreeNode) -> TreeNode:
You can’t perform that action at this time.
0 commit comments