二叉树的深度优先遍历和广度优先遍历-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 @ 2021-04-29 17:08  今夜无风  阅读(169)  评论(0编辑  收藏  举报