Python实现二叉树的存储和遍历

首先应该了解几个概念:

满二叉树,完全二叉树,非完全二叉树,下图来自百度百科

《Python实现二叉树的存储和遍历》

 

 

代码实现

class Node(object):
    """"树的节点类"""

    def __init__(self, item):
        self.item = item
        # 记录左孩子
        self.lChild = None
        # 记录右孩子
        self.rChild = None


class Tree(object):
    """"""

    def __init__(self):
        self.__root = None

    # 添加节点
    def add(self, item):
        node = Node(item)
        # 判断是否为空
        if self.__root is None:
            self.__root = node
        else:
            # 以队列的方式变量树
            queue = []
            queue.append(self.__root)

            while queue:
                cur = queue.pop(0)

                if cur.lChild is None:
                    cur.lChild = node
                    return
                if cur.rChild is None:
                    cur.rChild = node
                    return
                queue.append(cur.lChild)
                queue.append(cur.rChild)

    # 广度优先遍历,层次遍历
    def breath_travel(self):
        if self.__root is None:
            return

        # 以队列的方式进行遍历
        queue = []
        queue.append(self.__root)

        while queue:
            cur = queue.pop(0)
            print(cur.item)

            if cur.lChild is not None:
                queue.append(cur.lChild)
            if cur.rChild is not None:
                queue.append(cur.rChild)

    # 深度优先遍历
    def depth_travel(self):
        self.post_order(self.__root)

    # 后序
    def post_order(self, node):
        if node is None:
            return
        self.post_order(node.lChild)
        self.post_order(node.rChild)
        print(node.item, end=" ")

    # 中序
    def in_order(self, node):
        if node is None:
            return
        self.in_order(node.lChild)
        print(node.item, end=" ")
        self.in_order(node.rChild)

    # 先序
    def pre_order(self, node):
        if node is None:
            return
        print(node.item, end=" ")
        self.pre_order(node.lChild)
        self.pre_order(node.rChild)


if __name__ == '__main__':
    tree = Tree()
    tree.add(0)
    tree.add(1)
    tree.add(2)
    tree.add(3)
    tree.add(4)
    tree.add(5)
    tree.add(6)
    tree.add(7)
    tree.add(8)
    tree.add(9)
    # tree.breath_travel()
    tree.depth_travel()

 

    原文作者:GreatAnt
    原文地址: https://www.cnblogs.com/greatfish/p/6071490.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注