用python 实现二分查找树
时间: 2024-04-29 13:22:18 浏览: 99
python 实现 二分查找
好的,下面是用 Python 实现二分查找树的代码:
```
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert(self, val):
new_node = Node(val)
if self.root is None:
self.root = new_node
else:
current = self.root
while True:
if val < current.val:
if current.left is None:
current.left = new_node
break
else:
current = current.left
elif val > current.val:
if current.right is None:
current.right = new_node
break
else:
current = current.right
def search(self, val):
current = self.root
while current is not None:
if current.val == val:
return True
elif current.val > val:
current = current.left
else:
current = current.right
return False
```
以上是简单的二分查找树的 Python 实现,可以使用 `insert` 方法插入一个新节点,使用 `search` 方法查找指定值的节点是否存在。
阅读全文