二叉树层序遍历 python 版本

This commit is contained in:
WSL0809 2022-12-24 22:19:54 +08:00 committed by GitHub
parent 8733557f00
commit 2c462a6a78
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -65,7 +65,26 @@ comments: true
=== "Python"
```python title="binary_tree_bfs.py"
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
// 初始化一个列表,用于保存遍历序列
result = []
if not root :
return result
from collections import deque
// 初始化队列,加入根结点
queue = deque([root])
while queue:
list = []
size = len(queue)
for _ in range(size):
cur = queue.popleft()
list.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
result.append(list)
return result
```
=== "Go"