C++实现搜索二叉树
时间: 2023-07-11 20:14:40 浏览: 50
可以使用结构体和指针来实现搜索二叉树,具体实现方法如下:
```c++
#include <iostream>
using namespace std;
// 定义二叉树节点结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 插入节点
void insert(TreeNode*& root, int val) {
if (root == NULL) {
root = new TreeNode(val);
return;
}
if (root->val < val) {
insert(root->right, val);
} else {
insert(root->left, val);
}
}
// 中序遍历
void inorder(TreeNode* root) {
if (root == NULL) return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
int main() {
TreeNode* root = NULL;
int n, val;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> val;
insert(root, val);
}
inorder(root);
return 0;
}
```
以上代码实现了搜索二叉树的插入和中序遍历。其中,插入操作使用了递归实现,中序遍历则使用了递归遍历左子树、节点、右子树的方式输出节点的值。可以通过输入一组数来测试代码是否正确。