Wednesday, February 25, 2015

Binary Search Tree implementation in C++

/*
Binary Search Tree Implementation in C++
*/
#include<iostream>

using namespace std;

struct node{
int data;

node * left;
node * right;
} *root;


node * insert(node *root, int e){
if(root == NULL){
root = new node;
root->data = e;
return root;
} else if ((root->data) > e) {
root->left = insert(root->left,e);
} else if ((root->data) < e) {
root->right = insert(root->right,e);
}

return root;

}

node * search(node * root, int e){
if(root == NULL){
return NULL;
} else if(root->data == e){
return root;
} else if(root->data > e){
return search(root->left,e);
} else {
return search(root->right,e);
}
}

void makeTreeFromArray(int A[], int n){
for(int i=0; i<n;i++){
root = insert(root, A[i]);
}
}

void printTree(node  * root){
if(root){
//cout<<"(";
printTree(root->left);
cout<<root->data<<"  ";
printTree(root->right);
//cout<<")";
}
}

int countLeaves(node * root){
if(root == NULL){
return 0;
} else {
if( (root->left == NULL) && (root->right == NULL) ){
return 1;
} else {
return countLeaves(root->left) + countLeaves(root->right);
}
}
}
node * findMax(node * root){
if(root == NULL){
return NULL;
} else if(root->right == NULL){
return root;
} else {
return findMax(root->right);
}
}

node * deleteNode(node * root, int e){
if(root == NULL){
cout<<"Element not found";
} else if(e > root->data){
root->right = deleteNode(root->right, e);
} else if(e < root->data){
root->left = deleteNode(root->left, e);
} else {
if(root->left && root->right){
node * temp = findMax(root->left);
root->data = temp->data;
root->left = deleteNode(root->left, temp->data);
} else {
node * temp = root;
if(root->left){
root = root->left;
}else if(root->right){
root = root-> right;
} else {
root = NULL;
}
delete temp;
}
}
return root;
}



int main(){
int A[] = {6,2,10,1,3,8,11,7,9,5,4};
int n = 11;

makeTreeFromArray(A,n);
printTree(root);

cout<<"\n";

root = deleteNode(root, 6);
printTree(root);
cout<<"\nNumber of leaves : "<<countLeaves(root)<<"\n";
return 0;
}

No comments:

Post a Comment