python_二叉排序树实现

二叉排序树

# 节点
class Node:
    def __init__(self, elem):
        self.elem = elem
        self.left = None
        self.right = None


# 二叉排序树
class BinarySearchTree:
    def __init__(self):
        self.root = None

    def is_empty(self):
        return self.root is None

    def search(self, node):
        ''' 采用中序遍历 '''
        if not node:
            return
        self.search(node.left)
        print(node.elem, end=' ')
        self.search(node.right)

    def insert(self, key):
        ''' 对于任何一个节点,右子树的元素大于等于其本身,左子树的元素小于其本身 '''
        node = Node(key)
        if self.root is None:
            self.root = node
            return
        cur = self.root
        while cur:
            if node.elem < cur.elem:
                if cur.left is None:
                    cur.left = node
                    return
                else:
                    cur = cur.left
            elif node.elem >= cur.elem:
                if cur.right is None:
                    cur.right = node
                    return
                else:
                    cur = cur.right

    def delete(self,item):
        '''
           分三种情况:
                   1.要删除元素没有左右子树,为叶子节点或单独根节点,只需父节点对应指针为空即可
                   2.要删除元素有且只有左右子树, 只需父节点指针指向对应其子树节点
                   3.要删除元素含左右子树
       '''
        pass
        

if __name__ == '__main__':
    bst = BinarySearchTree()
    print(bst.is_empty())
    bst.insert(10)
    bst.insert(2)
    bst.insert(8)
    bst.insert(4)
    bst.insert(3)
    bst.insert(5)
    bst.insert(24)
    bst.insert(34)
    bst.insert(35)
    bst.insert(23)
    bst.insert(33)
    bst.search(bst.root)```
posted @ 2021-01-05 21:12  旁人怎会懂  阅读(284)  评论(0)    收藏  举报