c++编写代码实现用户输入一组数组,并能够查找元素完成二叉树的折半查找代码
时间: 2025-06-14 21:15:50 浏览: 6
在C++中,我们可以使用二分查找算法来构建一个折半查找功能。首先,我们需要创建一个二叉搜索树,然后让用户输入一个整数数组。以下是简单的步骤和代码实现:
```cpp
#include <iostream>
using namespace std;
// 定义二叉搜索树节点结构体
struct Node {
int data;
Node* left;
Node* right;
};
// 插入节点到二叉搜索树
Node* insert(Node* root, int value) {
if (root == nullptr) {
return new Node{value, nullptr, nullptr};
}
if (value < root->data)
root->left = insert(root->left, value);
else if (value > root->data)
root->right = insert(root->right, value);
return root;
}
// 折半查找函数
Node* binarySearch(Node* root, int target) {
while (root != nullptr) {
int mid = root->data; // 当前根节点值作为中间点
if (target == mid)
return root; // 找到了目标返回
else if (target < mid)
root = root->left; // 目标小于当前节点,向左半部分查找
else
root = root->right; // 目标大于当前节点,向右半部分查找
}
return nullptr; // 没有找到目标,返回nullptr
}
int main() {
Node* root = nullptr;
int n, value;
cout << "Enter the number of elements for array: ";
cin >> n;
cout << "Please enter the array elements one by one: ";
for(int i = 0; i < n; ++i) {
cin >> value;
root = insert(root, value);
}
int target;
cout << "Enter a number to search in the tree: ";
cin >> target;
Node* result = binarySearch(root, target);
if(result) {
cout << "Number found at position: " << result->data << endl;
} else {
cout << "Number not found in the tree." << endl;
}
return 0;
}
```
阅读全文
相关推荐












