码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的实现

时间:2020-05-02 14:51:38      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:__name__   poi   else   get   int   forward   one   sel   左右   

# 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)

 

二叉树的实现

标签:__name__   poi   else   get   int   forward   one   sel   左右   

原文地址:https://www.cnblogs.com/sun-10387834/p/12817768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!