二叉树的深度优先遍历和广度优先遍历-Python

复制代码
# 二叉树系列
class BinaryTree(object):
    def __init__(self, item):
        self.item = item
        self.left = None
        self.right = None

def create_tree_data():
    a = BinaryTree(1)
    b = BinaryTree(2)
    c = BinaryTree(3)
    d = BinaryTree(4)
    e = BinaryTree(5)
    f = BinaryTree(6)
    g = BinaryTree(7)

    a.left = b
    a.right = e
    b.left = c
    b.right = d
    e.left = f
    e.right = g
    return a

def xianxu_dfs(root):
    # 根左右,先访问根节点,再左右孩子
    print(root.item)
    if root.left:
        xianxu_dfs(root.left)
    if root.right:
        xianxu_dfs(root.right)

def zhongxu_dfs(root):
    # 左右根,先访问左右孩子,再根节点
    if not root:
        return
    if root.left:
        zhongxu_dfs(root.left)
    print(root.item)
    if root.right:
        zhongxu_dfs(root.right)

def houxu_dfs(root):
    if not root:
        return
    if root.left:
        houxu_dfs(root.left)
    if root.right:
        houxu_dfs(root.right)
    print(root.item)

from queue import Queue
def bfs(root):
    # 广度优先,逐层遍历,使用队列FIFO,存储层次数据
    q = Queue()
    q.put(root)
    while not q.empty():
        current_node = q.get()
        print(current_node.item)
        if current_node.left:
            q.put(current_node.left)
        if current_node.right:
            q.put(current_node.right)


if __name__ == '__main__':
    head = create_tree_data()
    # xianxu_dfs(head)
    # zhongxu_dfs(head)
    # houxu_dfs(head)
    bfs(head)
复制代码

 

posted @   今夜无风  阅读(170)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2020-04-29 根据传统的TFIDF快速进行相似性匹配
2020-04-29 用户推荐类知识点重塑
点击右上角即可分享
微信分享提示