#include<iostream>
#include<cstdio>
#include<queue>
#include<cmath>
#include<cstdlib>
using namespace std;
struct node
{
int data;
struct node*left;
struct node*right;
};
node tree;
struct node * create(int t)
{
node* tmp=new node;
tmp->data=t;
tmp->left=tmp->right=NULL;
return tmp;
}
struct node * insert(struct node *root,int t)
{
if(root==NULL)root=create(t);
if(root->data>t)root->left=insert(root->left,t);
else if(root->data<t)root->right=insert(root->right,t);
return root;
}
void preorder(struct node* root)
{
if(!root)return;
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
void levelorder(struct node *root)
{
if(!root)return;
queue<struct node*>q;
q.push(root);
while(!q.empty())
{
struct node *tmp=q.front();
q.pop();
printf("%d ",tmp->data);
if(tmp->left)q.push(tmp->left);
if(tmp->right)q.push(tmp->right);
}
}
int getheight(struct node* root)
{
if(!root)return 0;
int h1=getheight(root->left);
int h2=getheight(root->right);
return 1+max(h1,h2);
}
struct node* Findmin(struct node* root)
{
if(!root)return NULL;
struct node* tmp=root;
while(tmp->left)tmp=tmp->left;
return tmp;
}
struct node * Delete(struct node *root,int x)
{
if(!root)return NULL;
if(x<root->data)root->left=Delete(root->left,x);
else if(x>root->data)root->right=Delete(root->right,x);
else
{
struct node *tmp=root;
if(root->left&&root->right)
{
tmp=Findmin(root->right);
root->data=tmp->data;
root->right=Delete(root->right,root->data);
}
else
{
if(!root->left)root=root->right;
else if(!root->right)root=root->left;
else free(tmp);
}
}
return root;
}
int main()
{
struct node* root=NULL;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int t;
cin>>t;
root=insert(root,t);
}
preorder(root);//先序遍歷
cout<<endl;
levelorder(root);
cout<<endl;
cout<<getheight(root)<<endl;
Delete(root,4);
levelorder(root);
cout<<endl;
cout<<getheight(root)<<endl;
return 0;
}