二叉树的实现

复制代码
# coding:utf8
class Node():
    def __init__(self, _item):
        self.item = _item
        self.left = None
        self.right = None


class Tree():
    def __init__(self):
        self.root = None

    def append(self, _item):
        node = Node(_item)
        cur = self.root
        point_list = [cur]
        # 如果添加的是根节点
        if cur == None:
            self.root = node
            return
        while True:
            target_point = point_list.pop(0)
            if target_point.left == None:
                target_point.left = node
                return
            else:
                point_list.append(target_point.left)
            if target_point.right == None:
                target_point.right = node
                return
            else:
                point_list.append(target_point.right)

    # 广度优先搜索遍历
    def travel(self):
        cur = self.root
        point_list = [cur]
        while point_list:
            target_point = point_list.pop(0)
            print(target_point.item)
            if target_point.left:
                point_list.append(target_point.left)
            if target_point.right:
                point_list.append(target_point.right)

    # 深度优先搜索遍历
    def forward(self, root):  # 前序遍历 :根左右
        if root == None:
            return
        print(root.item)
        self.forward(root.left)
        self.forward(root.right)

    def middle(self, root):  # 中序遍历 :左根右
        if root == None:
            return
        self.middle(root.left)
        print(root.item)
        self.middle(root.right)

    def back(self, root):  # 后序遍历 :左右根
        if root == None:
            return
        self.back(root.left)
        self.back(root.right)
        print(root.item)


if __name__ == "__main__":
    tree = Tree()
    tree.append(1)
    tree.append(2)
    tree.append(3)
    tree.append(4)
    tree.append(5)
    tree.append(6)
    tree.append(7)
    # tree.travel()
    # tree.forward(tree.root)
    # tree.middle(tree.root)
    tree.back(tree.root)
复制代码

 

posted @   佛祖让我来巡山  阅读(111)  评论(0编辑  收藏  举报

佛祖让我来巡山博客站 - 创建于 2018-08-15

开发工程师个人站,内容主要是网站开发方面的技术文章,大部分来自学习或工作,部分来源于网络,希望对大家有所帮助。

Bootstrap中文网

点击右上角即可分享
微信分享提示