Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitadb27f2

Browse files
Merge pull requestyoungyangyang04#467 from Miraclelucy/master
Update 0617.合并二叉树.md - 增加了python3版本的迭代解法
2 parentsc1ac306 +33f2e45 commitadb27f2

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

‎problems/0617.合并二叉树.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ Python:
319319
# self.val = val
320320
# self.left = left
321321
# self.right = right
322-
//递归法*前序遍历
322+
#递归法*前序遍历
323323
classSolution:
324324
defmergeTrees(self,root1: TreeNode,root2: TreeNode) -> TreeNode:
325325
ifnot root1:return root2// 如果t1为空,合并之后就应该是t2
@@ -328,6 +328,32 @@ class Solution:
328328
root1.left=self.mergeTrees(root1.left , root2.left)//
329329
root1.right=self.mergeTrees(root1.right , root2.right)//
330330
return root1//root1修改了结构和数值
331+
332+
# 迭代法-覆盖原来的树
333+
classSolution:
334+
defmergeTrees(self,root1: TreeNode,root2: TreeNode) -> TreeNode:
335+
ifnot root1:return root2
336+
ifnot root2:return root1
337+
# 迭代,将树2覆盖到树1
338+
queue1= [root1]
339+
queue2= [root2]
340+
root= root1
341+
while queue1and queue2:
342+
root1= queue1.pop(0)
343+
root2= queue2.pop(0)
344+
root1.val+= root2.val
345+
ifnot root1.left:# 如果树1左儿子不存在,则覆盖后树1的左儿子为树2的左儿子
346+
root1.left= root2.left
347+
elif root1.leftand root2.left:
348+
queue1.append(root1.left)
349+
queue2.append(root2.left)
350+
351+
ifnot root1.right:# 同理,处理右儿子
352+
root1.right= root2.right
353+
elif root1.rightand root2.right:
354+
queue1.append(root1.right)
355+
queue2.append(root2.right)
356+
return root
331357
```
332358

333359
Go:

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp