二叉树的层序遍历(python)
时间: 2024-03-06 19:27:27 浏览: 84
二叉树的层序遍历.md
二叉树的层序遍历是一种广度优先搜索,它通过使用队列的思想来实现。每次从队列中取出一个节点,并将其子节点加入队列,从而逐层遍历整个二叉树。这样可以保证按照从上到下、从左到右的顺序访问每个节点。
下面是一个示例代码,用Python实现了二叉树的层序遍历:
```python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = [] # 结果
if root:
queue = [root # 第一层
else:
return res
while len(queue): # 当下一层没有子节点后停止遍历
n = len(queue)
r = []
for _ in range(n):
node = queue.pop(0) # 弹出第一个值
r.append(node.val)
if node.left: # 左子树判断
queue.append(node.left)
if node.right: # 右子树判断
queue.append(node.right)
res.append(r) # 加入一层的结果
return res
```
这段代码定义了一个Solution类,其中的levelOrder方法用于实现二叉树的层序遍历。通过创建一个队列,然后遍历每一层的节点,并将它们的值加入到结果列表中,最后返回结果列表即可。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Python二叉树的遍历操作示例【前序遍历,中序遍历,后序遍历,层序遍历】](https://download.csdn.net/download/weixin_38713009/12865510)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [常用算法](https://blog.csdn.net/weixin_30905981/article/details/96548613)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [二叉树的层序遍历Python解法](https://blog.csdn.net/qq_43593534/article/details/123800081)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文