广度遍历二叉树 python
时间: 2023-08-28 22:23:21 浏览: 100
要在Python中实现二叉树的广度优先遍历,可以使用队列来实现。下面是一个示例代码:
```python
class TreeNode(object):
def __init__(self, value, left_child=None, right_child=None):
self.left_child = left_child
self.value = value
self.right_child = right_child
def wide_search(root):
queue = [root]
while queue:
node = queue.pop(0)
print(node.value)
if node.left_child:
queue.append(node.left_child)
if node.right_child:
queue.append(node.right_child)
# 创建一个二叉树
node_a = TreeNode('A')
node_b = TreeNode('B')
node_c = TreeNode('C')
node_d = TreeNode('D')
node_e = TreeNode('E')
node_f = TreeNode('F')
node_g = TreeNode('G')
node_a.left_child = node_b
node_a.right_child = node_c
node_b.left_child = node_d
node_b.right_child = node_e
node_c.left_child = node_f
node_c.right_child = node_g
wide_search(node_a)
```
这段代码中,我们首先定义了一个`TreeNode`类来表示二叉树的节点。然后,我们定义了一个`wide_search`函数来实现广度优先遍历。在函数中,我们使用一个队列来存储待遍历的节点。我们从根节点开始,将根节点入队列,然后循环处理队列中的节点,每次处理一个节点时,将其值打印出来,并将其左右子节点分别入队列。这样就可以实现广度优先遍历了。最后,我们创建了一个二叉树的实例,并调用`wide_search`函数来进行广度优先遍历。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [python 深度、广度遍历二叉树](https://blog.csdn.net/weixin_42336579/article/details/81334212)[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^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *2* [python基础编程:python实现树的深度优先遍历与广度优先遍历详解](https://download.csdn.net/download/weixin_38590309/14855357)[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^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文