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

用python实现排序二叉树(中序)

程序员文章站 2024-03-19 22:53:16
...
class SortTree():

    def __init__(self):
        self.root = None

    def add(self, item):
        node = Node(item)

        cur = self.root

        if cur == None:
            self.root = node
            return

        while cur:

            if item > cur.item:

                if cur.right == None:
                    cur.right = node
                    break
                else:
                    cur = cur.right

            else:

                if cur.left == None:
                    cur.left = node
                    break
                else:
                    cur = cur.left

    def travle(self):

        cur = self.root

        q = [cur]
        while q:
            nd = q.pop(0)
            print(nd.item)
            if nd.left:
                q.append(nd.left)

            if nd.right:
                q.append(nd.right)
    def middle(self, root):

        if root == None:
            return

        self.middle(root.left)
        print(root.item)
        self.middle(root.right)



t = SortTree()

alist = [3, 8, 5, 7, 6, 2, 9, 4, 1]

for i in alist:
    t.add(i)

# t.travle()
t.middle(t.root)