gpt4 book ai didi

c++ - 插入 BST 导致错误 C++

转载 作者:行者123 更新时间:2023-11-28 03:30:01 26 4
gpt4 key购买 nike

我已经实现了 BST,当我插入一些值时,我在 INSERT 函数中遇到了错误。如果我将 main 函数中的 -32 替换为 32(see main) 它工作正常,但现在出现错误。我找不到它。

#include <iostream>
#include <cstdlib>
using namespace std;

struct Node{
int val;
Node* l;
Node* p;

Node(int val){
this->val = val;
l = NULL;
p = NULL;
}
};

struct BST{
Node* root;
BST(int val){
root = new Node(val);
}
};

bool insert(Node* e, int val){
if(e->val == val){
return false;
}
else if(val < e->val){
if(e->l == NULL){
e->l = new Node(val);
return true;
} else
return insert(e, val);
} else if(val > e->val){
if(e->p == NULL){
e->p = new Node(val);
return true;
}else
return insert(e->p, val);
} return false;
}

bool insert(BST* d, int val){
insert(d->root, val);
}

void infixDisplay(Node* w){
if(w != NULL){
infixDisplay(w->l);
cout<<w->val<<endl;
infixDisplay(w->p);
}
}

void infixDisplay(BST* d){
infixDisplay(d->root);
}

int main(){
BST* d = new BST(4);
insert(d,12);
insert(d,-32); // REPLACE WITH +32 IT IS OK!
insert(d,4);
insert(d,89);
insert(d,6);
insert(d,3);
infixDisplay(d);
return 0;
}

最佳答案

行:

return insert(e, val);

应该是

return insert(e->l, val);

关于c++ - 插入 BST 导致错误 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12865794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com