二叉搜索树的创建C++
时间: 2024-01-04 20:18:22 浏览: 31
以下是C++中创建二叉搜索树的示例代码:
```cpp
#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;
}
// 中序遍历二叉搜索树
void inorder(TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
int main() {
// 创建二叉搜索树
TreeNode* root = NULL;
root = insert(root, 5);
insert(root, 3);
insert(root, 7);
insert(root, 1);
insert(root, 9);
// 中序遍历二叉搜索树
inorder(root);
return 0;
}
```