C++正在创建二进制搜索树:EXC_BAD_ACCESS错误.算法错误还是编码错误



问题:我一直收到exc_bad_access(进程代码11)错误。这是由于糟糕的算法还是简单的编码错误?有人能帮我修吗

我的类作业是创建一个二进制搜索树,其节点可以存储名称、余额和关键字。要使用密钥来组织和搜索节点。这个树应该支持插入、有序遍历和基于键的搜索(我还没有构建这个函数)。我还包含了一些其他功能,以便于构建这些功能。如果重要的话,我在OSX High Sierra上使用CLion。此外,我在第一次提示输入节点信息时收到错误,该错误似乎与输入本身无关。

//Genghis Khan
#include <iostream>
#include <vector>
using namespace std;
class node
{
public:
int key;
string name;
double balance;
node *leftptr;
node *rightptr;
friend class tree;
};
class tree
{
public:
node *root, *temp, *v;
//Constructor
tree()
{
root = NULL;
temp = root;
}
bool empty()
{
return(root == NULL);
}

bool isleaf(node *x)
{
return((x->leftptr == NULL) && (x->rightptr == NULL));
}  
void inorder(node *temp)
{
if(~isleaf(temp)) 
{
inorder(temp->leftptr);
cout << "Name: " << temp->name << " " << "Balance: " << 
temp->balance << " " << "Key: " << temp->key;
inorder(temp->rightptr);
}
}
node* createnode()
{
v = new node;
cout << "Enter name (string): " << endl;
getline(cin, v->name); 
cout << "Enter key (integer): " << endl;
cin >> v->key;
cout << "Enter balance (double): " << endl;
cin >> v->balance;
return(v);
}
void set()
{
temp = root;
}
void insert(node *v)
{
while(~isleaf(temp)) 
{
if((v->key < temp->key))
{
temp = temp->leftptr;
insert(v);
}
else if(v->key > temp->key)
{
temp = temp->rightptr;
insert(v);
}
}
temp->key = v->key;
temp->balance = v->balance;
temp->name = v->name;
}
};
int main()
{
int n;
cout << "Enter number of people: ";
cin >> n;
//Creating instance of tree, inserting all data into tree
tree b;
for(int i = 0; i < n; i++)
{
b.set();
node *a = b.createnode();
b.insert(a);
}
//inorder part
b.set();
b.inorder(b.temp);
}

函数为(伪代码):

1. function isleaf(x): return(x's left pointer and x's right pointer are both NULL)
2. function set(): set temp to root //temp will be reset every time an insertion, traversal, or search occurs
3. function createnode(): 
v is  a new node
get all the fields for v 
return v
4. function insert(v)
while(not isleaf(temp)):  
-if(v's key < temp's key)
temp = temp's left pointer (to the lower value child node)    
insert(node *v)
-if(v's key > temp's key)  
temp = temp's right pointer (to the higher value child node)   
insert(node *v)  
end while  
duplicate v's data to temp, now that temp is a leaf
5. function inorder(temp):  
if(not isleaf(temp):  
inorder(temp's left pointer)  
output all info in temp node  
inorder(temp's right pointer)

主要算法

对于要输入的节点数:
1。设置
2。node*a=createnode
3。插入(a)

更新

错误似乎来自"if(((v->key<temp->key))"行。

EXC_BAD_ACCESS只是表示您试图访问无效内存。简单介绍一下,函数isleaf不会检查x是否为null。

可能有其他错误,您可以自行调试并查找。

相关内容

最新更新