根据无序vector构建二叉搜索树
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* insertNode(TreeNode* root, int val) {
if (!root) {
return new TreeNode(val);
}
if (val < root->val) {
root->left = insertNode(root->left, val);
} else if (val > root->val) {
root->right = insertNode(root->right, val);
}
return root;
}
TreeNode* buildBST(const std::vector<int>& nums) {
TreeNode* root = NULL;
for (const int& num : nums) {
root = insertNode(root, num);
}
return root;
}
bool searchBST(TreeNode* root, int val) {
if (!root) {
return false;
}
if (root->val == val) {
return true;
} else if (val < root->val) {
return searchBST(root->left, val);
} else {
return searchBST(root->right, val);
}
}
void inorderTraversal(TreeNode* root) {
if (root) {
inorderTraversal(root->left);
std::cout << root->val << " ";
inorderTraversal(root->right);
}
}
int main() {
vector<int> nums;
int num;
cout << "请输入数组: ";
while (cin >> num) {
nums.push_back(num);
if(cin.get() == '\n') {
break;
}
}
int target;
cin >> target;
TreeNode* root = buildBST(nums);
cout << "二叉搜索树中序遍历: ";
inorderTraversal(root);
cout << endl;
if (searchBST(root, target)) {
cout << "二叉搜索树中存在: " << target << endl;
} else {
cout << "二叉搜索树中不存在: " << target << endl;
}
return 0;
}