这个树搜索功能让我发疯.它返回 NULL,但不知何故主函数中的值发生了变化

This tree search function drives me crazy. It return NULL but somehow the value changes in the main function

本文关键字:何故主 函数 变化 发生了 NULL 功能 搜索 返回 发疯      更新时间:2023-10-16

我的项目由 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设置为递归调用的返回值。