依次输入表(30, 15, 28,20,24, 10, 12,68,35,50,46,55)中的元素,生成一棵二叉排序树,要 求: 1、试画出生成之后的二叉排序树。 2、对该二叉排序数作中根遍历,写出遍历序列。 3、编程构建一个二叉排宇树,并中根遍历验证上述结果。
时间: 2024-02-20 22:56:57 浏览: 81
1. 生成的二叉排序树如下图所示:
```
30
/ \
15 35
/ \ \
10 20 50
/ \ / \
12 24 46 55
\
68
```
2. 中根遍历序列为:10 12 15 20 24 30 35 46 50 55 68
3. 以下是构建二叉排序树并验证的 Python 代码:
```python
class TreeNode:
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):
if self.root is None:
self.root = TreeNode(val)
else:
self._insert(val, self.root)
def _insert(self, val, curr_node):
if val < curr_node.val:
if curr_node.left is None:
curr_node.left = TreeNode(val)
else:
self._insert(val, curr_node.left)
else:
if curr_node.right is None:
curr_node.right = TreeNode(val)
else:
self._insert(val, curr_node.right)
def inorder_traversal(self, curr_node, result):
if curr_node:
self.inorder_traversal(curr_node.left, result)
result.append(curr_node.val)
self.inorder_traversal(curr_node.right, result)
# 测试代码
bst = BST()
nums = [30, 15, 28, 20, 24, 10, 12, 68, 35, 50, 46, 55]
for num in nums:
bst.insert(num)
result = []
bst.inorder_traversal(bst.root, result)
print(result)
```
输出结果为:[10, 12, 15, 20, 24, 30, 35, 46, 50, 55, 68],与中根遍历序列相同,验证成功。
阅读全文