Update 0226.翻转二叉树.md

python层序遍历方法,和之前层序遍历一节的写法一致
This commit is contained in:
ZerenZhang2022
2022-12-19 15:32:28 -05:00
committed by GitHub
parent 3c110bd4c3
commit 83af7646e0

View File

@ -359,7 +359,22 @@ class Solution:
queue.append(node.right)
return root
```
迭代法:广度优先遍历(层序遍历),和之前的层序遍历写法一致:
```python
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root: return root
from collections import deque
que=deque([root])
while que:
size=len(que)
for i in range(size):
cur=que.popleft()
cur.left, cur.right = cur.right, cur.left
if cur.left: que.append(cur.left)
if cur.right: que.append(cur.right)
return root
```
### Go
递归版本的前序遍历