用c++从小到大输出二叉排序树中所有关键字不小于x的数据元素
时间: 2024-05-11 16:19:32 浏览: 7
以下是使用C++实现二叉排序树输出关键字不小于x的数据元素的代码:
```c++
#include <iostream>
using namespace std;
// 定义二叉排序树结点
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 向二叉排序树中插入一个结点
TreeNode* insert(TreeNode* root, int val) {
if (root == NULL) {
return new TreeNode(val);
}
if (val < root->val) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
// 中序遍历二叉排序树,输出不小于x的结点
void inorder(TreeNode* root, int x) {
if (root == NULL) {
return;
}
inorder(root->left, x);
if (root->val >= x) {
cout << root->val << " ";
}
inorder(root->right, x);
}
// 主函数
int main() {
// 构造二叉排序树
TreeNode* root = NULL;
int arr[] = {5, 3, 7, 1, 4, 6, 8};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n; i++) {
root = insert(root, arr[i]);
}
// 输出不小于x的结点
int x = 4;
inorder(root, x);
return 0;
}
```
运行结果为:
```
4 5 6 7 8
```
其中,`insert`函数用于向二叉排序树中插入一个结点,`inorder`函数用于中序遍历二叉排序树并输出不小于x的结点。在主函数中,我们构造了一个二叉排序树,并输出其中所有关键字不小于4的结点。