插入之后无异常,但删除操作之后遍历跑不出来
#include<bits/stdc++.h>
using namespace std;
struct Tree
{
int data;
Tree *left;
Tree *right;
Tree(int w=0):data(w),left(NULL),right(NULL){}
}tree;
inline Tree* setup(int w)
{
Tree* root=new Tree;
root->data=w;
root->left=root->right=NULL;
return root;
}
void remove(Tree* &root,int x)
{
Tree* find=root;
Tree* father=NULL;
while(find!=NULL && find->data != x)
{
father=find;
if(find->data>x) find=find->left;
else find=find->right;
}
if(find==NULL) return;
if(find->left != NULL && find->right != NULL)
{
Tree* findright=find->right;
Tree* finddata=find;
while(findright->left !=NULL)
{
finddata=findright;
findright=findright->left;
}
find->data=findright->data;
find=findright;
father=finddata;
}
Tree* child;
if(find->left!=NULL) child=find->left;
else if(find->right!=NULL) child=find->right;
else child=NULL;
if(father=NULL) root=child;
else if(father->left==find) father->left=child;
else father->right=child;
}
void insert(Tree* &root,int x)
{
if(root==NULL)
{
root=setup(x);
return ;
}
if(root->data > x) insert(root->left,x);
else insert(root->right,x);
}
void preorder(Tree* root)
{
if(root==NULL) return;
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
void postorder(Tree* root)
{
if(root==NULL) return;
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
void inorder(Tree* root)
{
if(root==NULL) return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
int main()
{
Tree* tree=NULL;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
insert(tree,x);
}
cout<<"操作前:"<<endl;
preorder(tree);
cout<<endl;
inorder(tree);
cout<<endl;
postorder(tree);
cout<<endl;
int x;
cout<<"插入:";
cin>>x;
insert(tree,x);
int f;
cout<<"删除:";
cin>>f;
remove(tree,f);
cout<<"操作后:"<<endl;
preorder(tree);
cout<<endl;
inorder(tree);
cout<<endl;
postorder(tree);
cout<<endl;
}