#include <cstdio>
using namespace std;
struct node
{
int data;
node* lchild;
node* rchild;
};
void search(node *root,int x)
{
if(root==NULL)
{
printf("Failed");
return;
}
if(x==root->data)
{
printf("%d",root->data);
}else if(x < root->data)
{
search(root->lchild,x);
}else{
search(root->rchild,x);
}
}
node *newNode(int x)
{
node* Node=new node;
Node->data = x;
Node->lchild=Node->rchild=NULL;
return Node;
}
void insert(node* &root,int x)
{
if(root==NULL)
{
root=newNode(x);
return;
}
if(root->data==x)
return;
if(x<root->data)
{
insert(root->lchild,x);
}else
insert(root->rchild,x);
}
node *Create(int data[],int n)
{
node *root=NULL;
for(int i=0;i<n;i++)
{
insert(root,data[i]);
}
return root;
}
node *findMax(node* root)
{
if(root->rchild!=NULL)
root = root->rchild;
return root;
}
node* findMin(node* root)
{
if(root->lchild!=NULL)
root = root->lchild;
return root;
}
void deleteNode(node* &root,int x)
{
if(root==NULL)
return;
if(root->data==x)
{
if(root->lchild==NULL && root->rchild==NULL)
{
root = NULL;
}else if(root->lchild !=NULL)
{
node *pre = findMax(root->lchild);
root->data = pre->data;
deleteNode(root->lchild,pre->data);
}else{
node *next = findMin(root->rchild);
root->data = next->data;
deleteNode(root->rchild,next->data);
}
}else if(x<root->lchild)
deleteNode(root->lchild,x);
else
deleteNode(root->rchild,x);
}