构造二叉检索树本题目构造一棵二叉检索树。要求读入n个整数,以0结束。最后输出这棵树的先序序列。
时间: 2023-12-21 22:05:24 浏览: 90
将已知数组元素构造一棵二叉树
5星 · 资源好评率100%
以下是Python实现:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def build_bst(nums):
root = None
for num in nums:
if num == 0:
break
root = insert_node(root, num)
return root
def insert_node(root, val):
if root is None:
return TreeNode(val)
if val < root.val:
root.left = insert_node(root.left, val)
else:
root.right = insert_node(root.right, val)
return root
def preorder_traversal(root):
if root is not None:
print(root.val, end=" ")
preorder_traversal(root.left)
preorder_traversal(root.right)
if __name__ == '__main__':
nums = []
while True:
num = int(input())
if num == 0:
break
nums.append(num)
root = build_bst(nums)
preorder_traversal(root)
```
输入样例:
```
5
2
8
1
3
7
9
0
```
输出样例:
```
5 2 1 3 8 7 9
```
阅读全文