欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

树的深度优先遍历与广度优先遍历

程序员文章站 2022-03-03 11:36:12
...

深度优先有三种遍历方式,用递归实现

#递归实现先序遍历
def preorder(self, tree):
    if tree:
        print(tree.root)
        self.preorder(tree.lchild)
        self.preorder(tree.rchild
#递归实现中序遍历
def preorder(self,tree):
    if tree:
        self.preorder(tree.lchild)
        print(tree.root)
        self.preorder(tree.rchild)
#递归实现后序遍历
def preorder(self, tree):
    if tree:
        self.preorder(tree.lchild)
        self.preorder(tree.rchild)
        print(tree.root)
广度优先遍历用队列的方式实现
from pythonds.basic.queue import Queue
#利用队列实现树的广度优先遍历
def breadth_travel(self, tree):
    if tree :
        queue = []
        node = tree
        queue.append(tree)
        while queue:
            node = queue.pop(0)
            print(node.elem)
            if node.lchild != None:
                queue.append(node.lchild)
            if node.rchild != None:
                queue.append(node.rchild)
相关标签: python 二叉树