输入10个不同整数,依次插入到一颗初始为空的二叉排序树中,并对其进行中序遍历,以验证树的正确性的代码
时间: 2023-12-06 16:45:26 浏览: 53
以下是Python代码实现:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert_into_bst(root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert_into_bst(root.left, val)
else:
root.right = insert_into_bst(root.right, val)
return root
def inorder_traversal(root):
if not root:
return
inorder_traversal(root.left)
print(root.val, end=' ')
inorder_traversal(root.right)
# 测试
nums = [5, 2, 7, 3, 9, 1, 8, 4, 6, 10]
root = None
for num in nums:
root = insert_into_bst(root, num)
inorder_traversal(root)
```
输出结果为:`1 2 3 4 5 6 7 8 9 10`,表示二叉排序树构建并遍历成功。
阅读全文
相关推荐
















