程序運行後會崩潰什麼是我的程序(二叉搜索樹)的段錯誤
下面是我的整個程序。
它具有分段錯誤,但我不知道怎麼糾正
程序將會崩潰運行
下面是我的整個程序之後。
有段錯誤,但我不知道怎麼糾正
#include<iostream>
using namespace std;
class BinarySearchTree
{
public:
struct Node
{
int element;
Node *left;
Node *right;
Node(const int &ele,Node *lt,Node *rt)
:element{ele},left{lt},right{rt} {}
};
Node *root;
void insert(const int &ele)
{
insert(ele,root);
}
void in_order()
{
inorder(root);
}
void post_order()
{
postorder(root);
}
void desc_order()
{
descorder(root);
}
void remove(int x)
{
remove(x,root);
}
void pre_order()
{
preorder(root);
}
BinarySearchTree()
{
root==NULL;
}
~BinarySearchTree()
{
makeEmpty(root);
}
void makeEmpty(Node* & t)
{
if(t!= NULL)
{
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
t=NULL;
}
void insert(const int &x,Node * & t)
{
if(t==NULL)
t=new Node{x,NULL,NULL};
else if(x<t->element)
insert(x,t->left);
else if(x>t->element)
insert(x,t->right);
}
void inorder(Node *r)
{
if(r!=NULL)
{
postorder(r->left);
cout<<r->element<<" ";
postorder(r->right);
}
}
void postorder(Node *r)
{
if(r!=NULL)
{
postorder(r->left);
postorder(r->right);
cout<<r->element<<" ";
}
}
void preorder(Node *r)
{
if(r!=NULL)
{
cout<<r->element<<" ";
postorder(r->left);
postorder(r->right);
}
}
void descorder(Node *r)
{
if(r!=NULL)
{
postorder(r->right);
cout<<r->element<<" ";
postorder(r->left);
}
}
Node *findmin(Node*t)
{
if(t==NULL)
return NULL;
if(t->left==NULL)
return t;
return findmin(t->left);
}
void remove(int x, Node * &t)
{
if(t==NULL)
return;
if(x<t->element)
remove(x,t->left);
else if(t->element<x)
remove(x,t->right);
else if(t->left!=NULL&&t->right!=NULL)
{
t->element=findmin(t->right)->element;
remove(t->element,t->right);
}
else
{
Node *oldNode=t;
t=(t->left!=NULL)?t->left:t->right;
delete oldNode;
}
}
};
int main()
{
BinarySearchTree BST;
int N;
cin>>N;
int ele;
for(int i=0; i<N; i++)
{
cin>>ele;
BST.insert(ele);
}
cout<<"PRE_ORDER:";
BST.pre_order();
cout<<endl;
cout<<"IN_ORDER:";
BST.in_order();
cout<<endl;
cout<<"POST_ORDER:";
BST.post_order();
cout<<endl;
cout<<"DESCENDING_ORDER:";
BST.desc_order();
cout<<endl;
int dele;
cin>>dele;
BST.remove(dele);
cout<<"NEW TREE AFTER DELETING "<<dele<<endl;
cout<<"PRE_ORDER:";
BST.pre_order();
cout<<endl;
cout<<"IN_ORDER:";
BST.in_order();
cout<<endl;
cout<<"POST_ORDER:";
BST.post_order();
cout<<endl;
cout<<"DESCENDING_ORDER:";
BST.desc_order();
return 0;
}
爲什麼我的程序不能運行? 衷心感謝您的幫助
使用調試器,並通過你的程序步驟。投票結束。 –
根分配錯誤 –