#include <iostream> using namespace std; //二分查找 int bin_search(int A[], int n, int x) { int mid, low = 0, high = n - 1; //初始化查找区域 while (low <= high) //结束查找 { mid = (low + high) / 2; if (x == A[mid]) return mid; else if (x < A[mid]) high = mid - 1; else low = mid + 1; } return -1; //返回查找失败标记 } //二叉排序树 class Bnode { public: int date; Bnode* lchild,* rchild; }; void insert(Bnode* T, Bnode* S) { if (T == nullptr)T = S; else if (S->date < T->date) insert(T->lchild, S); else insert(T->rchild, S); } Bnode* creat() { Bnode* T = new Bnode; T = nullptr; int num = 0; cout << "输入结点数:"; cin >> num; cout << endl << "输入结点:" << endl; for (int i = 1; i <= num; i++) { Bnode* P = new Bnode; cin >> P->date; P->lchild = nullptr; P->rchild = nullptr; insert(T, P); } return T; } void InorderTree(Bnode *T) { if (T == nullptr) return; InorderTree(T->lchild); cout << T->date; InorderTree(T->rchild); } int main() { //二分查找 //int A1[] = { 1,2,3,4,6,7,8,9,10,11,12,13,17,18,19,20,24,25,26,30,35,40,45,50,100 }; //int A2[] = { 2,3,5,7,8,10,12,15,18,20,22,25,30,35,40,45,50,55,60, 80,100 }; //cout << "2:" << bin_search(A1, 26, 2) << " " // << "30:" << bin_search(A1, 26, 30) << " " // << "5:" << bin_search(A1, 26, 5) << " " // << "33:" << bin_search(A1, 26, 33) << " " // << "110:" << bin_search(A1, 26, 110) << endl // << "8:" << bin_search(A2, 21, 8) << " " // << "80:" << bin_search(A2, 21, 80) << " " // << "3:" << bin_search(A2, 21, 3) << " " // << "100:" << bin_search(A2, 21, 100) << " " // << "13:" << bin_search(A2, 21, 13) << endl; //二叉排序树 Bnode* T = creat(); InorderTree(T); return 0; }改错
时间: 2024-03-06 21:52:01 浏览: 108
使用include <iostream>时一定要加using namespace std
这段代码有一些错误,我会尝试指出并给出修改建议:
1. 在二叉排序树中的 insert 函数中,如果 T 为 nullptr,即为空指针,那么无法将 S 插入到 T 中,因为 T 本身就是 nullptr。正确的做法是将 T 的地址传递给 insert 函数,即使用指针的引用。修改后的代码如下:
```
void insert(Bnode*& T, Bnode* S) {
if (T == nullptr) T = S;
else if (S->date < T->date) insert(T->lchild, S);
else insert(T->rchild, S);
}
```
2. 在创建二叉排序树时,creat 函数返回的是一个指向根节点的指针,但是在 main 函数中没有接收该指针,也没有对该指针进行释放。正确的做法是在 main 函数中接收该指针,并在程序结束时手动释放该指针。修改后的代码如下:
```
int main() {
// ...
Bnode* root = creat();
InorderTree(root);
delete root;
return 0;
}
```
3. 在中序遍历二叉排序树时,应该在输出节点值后加上空格,方便观察。修改后的代码如下:
```
void InorderTree(Bnode* T) {
if (T == nullptr) return;
InorderTree(T->lchild);
cout << T->date << " ";
InorderTree(T->rchild);
}
```
阅读全文