#include<iostream>
#include<queue>
using namespace std;
struct BSTNode{
int data;
BSTNode *left,*right;
BSTNode(int x,BSTNode* L=NULL,BSTNode* R=NULL){
data=x;
left=L;
right=R;
}
};
class BST{
public:
BSTNode* root=NULL;
public:
BST(int arr[],int n){
for(int i=0;i<n;i++){
Insert(arr[i]);
}
}
BSTNode* Search(int x){
Search(x,root);
}
BSTNode* Search(int x,BSTNode* ptr){
if(ptr==NULL){
return NULL;
}else if(x<ptr->data){
return Search(x,ptr->left);
}else if(x>ptr->data){
return Search(x,ptr->right);
}else{
return ptr;
}
}
bool Insert(int x){
Insert(x,root);
}
bool Insert(int x,BSTNode* &ptr){
if(ptr==NULL){
ptr=new BSTNode(x);
return true;
}else if(x<ptr->data){
Insert(x,ptr->left);
}else if(x>ptr->data){
Insert(x,ptr->right);
}else{
return false;
}
}
bool Remove(int x){
Remove(x,root);
}
bool Remove(int x,BSTNode* &ptr){
BSTNode* temp;
if(ptr!=NULL){
if(x<ptr->data){
Remove(x,ptr->left);
}else if(x>ptr->data){
Remove(x,ptr->right);
}else if(ptr->left!=NULL&&ptr->right!=NULL){
temp=ptr->right;
while(temp->left!=NULL){
temp=temp->left;
}
ptr->data=temp->data;
Remove(ptr->data,ptr->right);
}else{
temp=ptr;
if(ptr->left==NULL){
ptr=ptr->right;
}else{
ptr=ptr->left;
}
delete temp;
return true;
}
}
return false;
}
void LevelTraversal(){
if(root!=NULL){
queue<BSTNode*> Q;
BSTNode* p=root;
Q.push(p);
while(!Q.empty()){
p=Q.front();
cout<<p->data<<" ";
Q.pop();
if(p->left!=NULL){
Q.push(p->left);
}
if(p->right!=NULL){
Q.push(p->right);
}
}
}
}
};
int main(){
int arr[]={53,17,78,9,45,65,87,23,81,94};
BST bst(arr,sizeof(arr)/sizeof(int));
bst.LevelTraversal();
cout<<endl;
bst.Remove(94);
bst.LevelTraversal();
cout<<endl;
bst.Insert(100);
bst.LevelTraversal();
cout<<endl;
return 0;
}