#include <iostream>
#include <string.h>
#include <stdio.h>
#include <list>
#include <vector>
#include <stdlib.h>
#include <queue>
using namespace std;
typedef struct node
{
node *left;
node *right;
int data;
}node;
node* insert(node *&tree,int data)
{
if(tree)
{
if(tree->data>data)
tree->left = insert(tree->left,data);
else
tree->right = insert(tree->right,data);
}
else
{
node *tree = (node *)malloc(sizeof(node));
tree->data = data;
tree->left = tree->right = NULL;
return tree;
}
return tree;
}
int ok = 1;
node *root1 = NULL;
void inorder(node *root)
{
if(root)
{
inorder(root->left);
if(ok == 1&&((!root->left&&!root->right)||(!root->left&&root->right)))
{
cout<<root->data;
ok = 0;
}
else
cout<<" "<<root->data;
inorder(root->right);
}
}
node *Del(node *tree,int data)
{
if(!tree)
{
return NULL;
}
else
{
if(tree->data>data)
{
tree->left = Del(tree->left,data);
}
else if(tree->data<data)
{
tree->right = Del(tree->right,data);
}
else
{
node *temp = tree;
if(!tree->left)
{
tree = tree->right;
free(temp);
}
else if(!tree->right)
{
tree = tree->right;
free(temp);
}
else
{
node *p = tree->right;
while(p&&p->left)
{
p = p->left;
}
tree->data = p->data;
Del(tree->right,p->data);
}
}
}
return tree;
}
int main()
{
root1 = NULL;
string cmd;
int temp;
while(true)
{
cin>>cmd;
ok = 1;
if(cmd=="add")
{
cin>>temp;
root1 = insert(root1,temp);
}
else if(cmd=="del")
{
cin>>temp;
root1 = Del(root1,temp);
}
inorder(root1);
cout<<endl;
}
}
09-10
09-10