#include<stdio.h>
#include<iostream>
using namespace std;
typedef struct Node
{
int data;
struct Node *lchild;
struct Node *rchild;
}Node,*pNode;
void create(pNode &tree,int data)
{
pNode ptr;
if(data == -1)
{
return;
}
if(tree == NULL)
{
tree = (pNode)malloc(sizeof(Node));
if(tree!=NULL)
{
tree->data = data;
tree->lchild = NULL;
tree->rchild = NULL;
}
return ;
}
if(tree->data>=data)
{
if(tree->lchild == NULL)
{
ptr = (pNode)malloc(sizeof(Node));
if(ptr!=NULL)
{
ptr->data = data;
ptr->lchild = NULL;
ptr->rchild = NULL;
}
tree->lchild = ptr;
}
else
{
create(tree->lchild,data);
}
}
if(tree->data<data)
{
if(tree->rchild == NULL)
{
ptr = (pNode)malloc(sizeof(Node));
if(ptr!=NULL)
{
ptr->data = data;
ptr->lchild = NULL;
ptr->rchild = NULL;
}
tree->rchild = ptr;
}
else
{
create(tree->rchild,data);
}
}
}
void inorderTravel(pNode tree)
{
if(tree)
{
inorderTravel(tree->lchild);
printf("%d ",tree->data);
inorderTravel(tree->rchild);
}
}
void preTravel(pNode tree)
{
if(tree)
{
printf("%d ",tree->data);
preTravel(tree->lchild);
preTravel(tree->rchild);
}
}
void postTravel(pNode tree)
{
if(tree)
{
postTravel(tree->lchild);
postTravel(tree->rchild);
printf("%d ",tree->data);
}
}
void DeleteNode(pNode &tree)
{
pNode ptr;
ptr = tree;
//如果右子树为空,左子树为空
if(ptr->rchild == NULL &&ptr->lchild==NULL)
{
free(ptr);
tree = NULL;
}
else if(ptr->rchild == NULL&&ptr->lchild!=NULL)
{
//找到前继节点
ptr->data = ptr->lchild->data;
DeleteNode(ptr->lchild);
}
else if(ptr->rchild != NULL&&ptr->lchild==NULL)
{
ptr->data = ptr->rchild->data;
DeleteNode(ptr->rchild);
}
else
{
ptr->data = ptr->lchild->data;
DeleteNode(ptr->lchild);
}
}
void deleteData(pNode &tree,int data)
{
if(!tree)
{
return ;
}
if(data == tree->data)
{
return DeleteNode(tree);
}
else if(data < tree->data)
{
return deleteData(tree->lchild,data);
}
else
{
return deleteData(tree->rchild,data);
}
}
int main(void)
{
pNode ptree = NULL;
pNode ptr = NULL;
int data = -2;
int i=0;
cin>>data;
while(data!=-1)
{
create(ptree,data);
cin>>data;
}
preTravel(ptree);
cout<<endl;
inorderTravel(ptree);
cout<<endl;
postTravel(ptree);
cout<<endl;
data = -2;
while(1)
{
cin>>data;
if(data==-1)
{
break;
}
deleteData(ptree,data);
inorderTravel(ptree);
cout<<endl;
}
getchar();
}