#include <iostream>
using namespace std;
typedef struct BinarySearchTree
{
int data;
int count;
struct BinarySearchTree* left;
struct BinarySearchTree* right;
BinarySearchTree()
{
}
BinarySearchTree(int x)
{
this->data=x;
this->count=1;
this->left=NULL;
this->right=NULL;
}
}BinarySearchTree;
BinarySearchTree* findX(BinarySearchTree* root,int x)
{
if(root->data==x)
return root;
else if(root->data<x)
{
return findX(root->right,x);
} else
{
return findX(root->left,x);
}
}
BinarySearchTree* find_X(BinarySearchTree* root,int x)
{
while(root)
{
if(root->data==x)
{
return root;
} else if(root->data>x)
{
root=root->left;
} else
{
root=root->right;
}
}
return NULL;
}
void insertX(BinarySearchTree* &root,int x)
{
if(!root)
{
root=new BinarySearchTree(x);
} else
{
if(root->data>x)
{
insertX(root->left,x);
} else
{
insertX(root->right,x);
}
}
}
void deleteX(BinarySearchTree* &root,int x)
{
if(root==NULL){
return ;
} else
{
if(root->data==x)
{
if(!root->left&&!root->right)
{
root=NULL;
}
else if(root->left)
{
BinarySearchTree* p=root->left;
while(p->right)
{
p=p->right;
}
p->right=root->right;
p->left=root->left;
root=p;
p=NULL;
}
else
{
BinarySearchTree* p=root->right;
while(p->right)
{
p=p->right;
}
p->right=root->right;
root=p;
p=NULL;
}
} else if(root->data>x)
{
deleteX(root->left,x);
} else
{
deleteX(root->right,x);
}
}
}
void init(BinarySearchTree* &root)
{
int n;
cin>>n;
for (int i = 0; i < n; ++i) {
int x;
cin>>x;
insertX(root,x);
}
}
void preorder(BinarySearchTree* root)
{
if(root)
{
preorder(root->left);
cout<<root->data<<" "<<root->count<<endl;
preorder(root->right);
}
}
int main() {
BinarySearchTree* root=NULL;
init(root);
preorder(root);
int x;
cin>>x;
BinarySearchTree* res=findX(root,x);
if(res)
{
res->count+=1;
} else
{
insertX(root,x);
}
cout<<"操作之后----------"<<endl;
preorder(root);
cout<<"删除之后----------"<<endl;
cin>>x;
deleteX(root,x);
preorder(root);
return 0;
}