用python写一个二叉搜索树算法
时间: 2024-05-02 18:21:34 浏览: 13
以下是一个简单的二叉搜索树算法的Python实现:
```python
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, value):
new_node = Node(value)
if self.root is None:
self.root = new_node
else:
current_node = self.root
while True:
if value < current_node.value:
if current_node.left is None:
current_node.left = new_node
break
else:
current_node = current_node.left
else:
if current_node.right is None:
current_node.right = new_node
break
else:
current_node = current_node.right
def search(self, value):
current_node = self.root
while current_node is not None:
if value == current_node.value:
return True
elif value < current_node.value:
current_node = current_node.left
else:
current_node = current_node.right
return False
```
这个二叉搜索树类有两个主要的方法:`insert`和`search`。`insert`方法用于将一个新的值插入到树中,`search`方法用于查找一个给定的值是否在树中存在。这个实现使用了一个`Node`类来表示树中的节点。每个节点包含一个值,以及左右子树的引用。在`insert`方法中,我们从根节点开始,沿着树向下移动,直到找到一个合适的位置将新值插入。在`search`方法中,我们也从根节点开始,沿着树向下移动,直到找到给定的值或者到达叶子节点。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)