这个树搜索功能让我发疯.它返回 NULL,但不知何故主函数中的值发生了变化
This tree search function drives me crazy. It return NULL but somehow the value changes in the main function
我的项目由 3 个文件组成:
树.h
#ifndef TREE_H
#define TREE_H
struct nodo{
char val;
nodo *left;
nodo *right;
};
typedef nodo * tree;
bool isNull(tree &t);
void init(tree &t);
bool insert(tree &t, char c);
tree search(tree &t, char elem);
void print(tree &t);
#endif // TREE_H
树.cpp
#include <iostream>
#include "tree.h"
using namespace std;
static bool isEmpty(tree &t){
return (t==NULL);
}
bool isNull(tree &t){
return (t==NULL);
}
void init(tree &t){
t = NULL;
}
bool insert(tree &t, char c){
bool res = false;
if(isEmpty(t)){
t = new (nothrow) nodo;
if(t!=NULL){
t->left = NULL;
t->right = NULL;
t->val = c;
res = true;
} else {
res = false;
}
} else if(c <= t->val){
insert(t->left, c);
} else if(c > t->val){
insert(t->right, c);
}
return res;
}
tree search(tree &t, char elem){
tree res;
if(isNull(t)){
res = NULL;
} else if(elem== t->val){
res = t;
} else if(elem < t->val){
search(t->left, elem);
} else if(elem > t->val){
search(t->right, elem);
}
return res;
}
void print(tree &t){
if(!isNull(t)){
print(t->left);
cout << t->val << " ";
print(t->right);
}
}
和主要
#include <iostream>
#include "tree.h"
using namespace std;
int main(){
int op;
char car;
tree t;
init(t);
tree found;
do{
cout << "1. Insert" << endl;
cout << "2. Search" << endl;
cout << "3. Print" << endl;
cout << "4. Exit" << endl;
cout << "Choose one-> ";
cin >> op;
switch(op){
case 1:
cout << "Element to insert: ";
cin >> car;
insert(t, car);
break;
case 2:
cout << "Element to look for: ";
cin >> car;
found = search(t, car);
if(!isNull(found)){
cout << "Found!" << endl;
} else {
cout << "Not found" << endl;
}
break;
case 3:
cout << endl;
print(t);
cout << endl;
break;
}
}while(op>=1 && op <=3);
}
当我尝试搜索树中不包含的值时,函数成功返回 NULL,但在 main 函数中值以某种方式更改并且它不再是 NULL。我已经研究了几个小时,没有任何成功,挫败感很高。
如果您能帮助我修复错误,我将不胜感激。也尝试调试,但没有任何成功。
顺便说一下,树是节点* 的别名
仅当
满足前两个if
条件之一时,您的search()
才会设置 res
的值。
对于其余两种情况,如果需要进行递归调用,则 res
的值保持不变,并且递归调用的结果将被忽略。将返回指向类的未初始化指针,从而导致未定义的行为。
因此,当main()
调用 search()
时,只有根元素相对于前两个条件的状态才会产生定义的行为。
您应该能够通过修复最后两个 if
语句来解决此问题,以便将res
设置为递归调用的返回值。
相关文章:
- 从 c 或 cpp 系列子函数返回到主函数
- 主函数参数的属性
- 如何在主函数中调用模板类
- 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
- "Missing type specifier - int assumed"无法通过向主函数添加"return 0"来解决
- 我在主函数的左括号上不断收到错误,消息为obj\Debug\main.o||在函数"ZN11linked_listC1Ev"中:|
- 我可以在Visual Studio 2019上的项目下使用多个主函数吗?
- 修改链表主函数代码,用户将在其中输入节点的索引和数据以及正确的消息
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组
- ld 链接器错误,未定义对主函数的引用
- 为什么主函数在 C/C++ 中首先运行?
- 在主函数中使用wchar_t
- 主函数体未检测到对重载可变变量模板化函数C++的调用
- 当我链接两个静态C++库时,我可以在两个主函数库中有两个主要功能吗?
- 将其他函数中的变量用于主函数C++
- 如何在主函数中直接使用锁
- 如何使用 clang 仅获取主函数的 AST
- 如何在主函数之外访问数组?
- 函数,从问题中获取输入,并在主函数中使用该输入
- 这个树搜索功能让我发疯.它返回 NULL,但不知何故主函数中的值发生了变化