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

PYTHON实现二叉树的层次遍历,先序遍历,中序遍历,后序遍历

程序员文章站 2022-06-17 19:53:18
...

介绍:

树是数据结构中非常重要的一种,主要的用途是用来提高查找效率,对于要重复查找的情况效果更佳,如二叉排序树、FP-树。另外可以用来提高编码效率,如哈弗曼树。

PYTHON实现二叉树的层次遍历,先序遍历,中序遍历,后序遍历

代码:

class Node(object):
    """节点类"""
    def __init__(self, elem):
        self.elem = elem
        self.lchild = None
        self.rchild = None


class Tree(object):
    """树类"""
    def __init__(self):
        self.root = None

    def add(self, elem):
        """为树添加节点"""
        node = Node(elem)
        if self.root is None:
            self.root = node
            return
        queue = [self.root]
        '''队列来存储节点'''
        while queue:
            cur_node = queue.pop(0)
            '''层次遍历,找到插入节点的位置'''
            if cur_node.lchild is None:
                cur_node.lchild = node
                return
            else:
                 queue.append(cur_node.lchild)
            if cur_node.rchild is None:
                cur_node.rchild = node
                return
            else:
                 queue.append(cur_node.rchild)

    '''广度遍历'''
    def breadth_travel(self):
        if self.root is None:
            return
        queue = [self.root]
        while queue:
            cur_node = queue.pop(0)
            print(cur_node.elem,end=' ')
            if cur_node.lchild is not None:
                queue.append(cur_node.lchild)
            if cur_node.rchild is not None:
                queue.append(cur_node.rchild)
    '''先序遍历'''
    def preorder(self,node):
        if node is None:
            return
        print(node.elem,end=' ')
        self.preorder(node.lchild)
        self.preorder(node.rchild)

    '''中序遍历'''
    def inorder(self,node):
        if node is None:
             return
        self.inorder(node.lchild)
        print(node.elem,end=' ')
        self.inorder(node.rchild)

    '''后序遍历'''
    def postorder(self, node):
        if node is None:
            return
        self.postorder(node.lchild)
        self.postorder(node.rchild)
        print(node.elem,end=' ')

tree = Tree()
for i in range(10):
    tree.add(i)
print("层次遍历:")
tree.breadth_travel()
print()
print("先序遍历:")
tree.preorder(tree.root)
print()
print("中序遍历:")
tree.inorder(tree.root)
print()
print("后序遍历:")
tree.postorder(tree.root)

运行结果:
PYTHON实现二叉树的层次遍历,先序遍历,中序遍历,后序遍历