python用类实现二叉排序树
时间: 2023-10-16 11:30:39 浏览: 71
python实现的二叉树排序
以下是使用 Python 实现二叉搜索树的类代码:
```python
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, key):
if self.root is None:
self.root = Node(key)
else:
self._insert(key, self.root)
def _insert(self, key, node):
if key < node.val:
if node.left is None:
node.left = Node(key)
else:
self._insert(key, node.left)
elif key > node.val:
if node.right is None:
node.right = Node(key)
else:
self._insert(key, node.right)
def inorder_traversal(self, node):
if node is not None:
self.inorder_traversal(node.left)
print(node.val),
self.inorder_traversal(node.right)
def search(self, key):
return self._search(key, self.root)
def _search(self, key, node):
if node is None or node.val == key:
return node
if key < node.val:
return self._search(key, node.left)
else:
return self._search(key, node.right)
```
上面的代码包括了二叉搜索树的插入,中序遍历和搜索方法。在这里,我们使用了一个 `Node` 类来表示二叉树中的节点,并使用 `BinarySearchTree` 类来实现二叉搜索树的操作。
阅读全文