十大排序、七大查找算法python实现——二叉树查找

十大排序、七大查找算法python实现——二叉树查找

 

class BSTNode:
    def __init__(self, item, left= None, right = None):
        self.item = item
        self.left = left
        self.right = right
        
class BinarySortTree:
    def __init__(self):
        self.root = None
        
    def insert(self, item):
        bt = self.root
        if self.root is None:
            self.root = BSTNode(item)
            return
        while True:
            if item > bt.item:
                if bt.right is None:
                    bt.right = BSTNode(item)
                    return
                else:
                    bt = bt.right
                
            elif item < bt.item:
                if bt.left is None:
                    bt.left = BSTNode(item)
                    return
                else:
                    bt = bt.left
            else:
                bt.item = item
                return
            
    def search(self, key):
        bt = self.root
        while bt:
            if bt.item < key:
                bt = bt.right
            elif bt.item > key:
                bt = bt.left
            else:
                return True
        return False
                
    
    def __iter__(self):
        """
        实现二叉树的中序遍历算法,
        展示我们创建的二叉查找树.
        直接使用python内置的列表作为一个栈。
        :return: data
        """
        stack = []
        node = self.root
        while node or stack:
            while node:
                stack.append(node)
                node = node.left
            node = stack.pop()
            yield node.item
            node = node.right

 

 

if __name__ == '__main__':
    lis = random_list(1,100,20)
    bs_tree = BinarySortTree()

    for i in range(len(lis)):
        bs_tree.insert(lis[i])

    for i in bs_tree:
        print(i, end=" ")

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值