链式存储结构构建二叉排序树python代码实现
时间: 2023-07-26 07:39:28 浏览: 97
以下是链式存储结构构建二叉排序树的Python代码实现:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, val):
if not self.root:
self.root = TreeNode(val)
else:
self._insert(val, self.root)
def _insert(self, val, node):
if val < node.val:
if node.left is None:
node.left = TreeNode(val)
else:
self._insert(val, node.left)
else:
if node.right is None:
node.right = TreeNode(val)
else:
self._insert(val, node.right)
def inorder_traversal(self):
if not self.root:
return []
return self._inorder_traversal(self.root, [])
def _inorder_traversal(self, node, res):
if node:
self._inorder_traversal(node.left, res)
res.append(node.val)
self._inorder_traversal(node.right, res)
return res
```
使用方法:
```python
bst = BinarySearchTree()
bst.insert(8)
bst.insert(3)
bst.insert(10)
bst.insert(1)
bst.insert(6)
bst.insert(14)
bst.insert(4)
bst.insert(7)
bst.insert(13)
print(bst.inorder_traversal())
```
输出结果:
```
[1, 3, 4, 6, 7, 8, 10, 13, 14]
```
阅读全文