BST Tree Implementation

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

//#include<mar jao>

//#include<moti.sophia>
#include<iostream>
using namespace std;

struct node
{
int data;
node* left;
node* right;
};
class tree
{
private:
node* temp;

public:

node* newNode(int d)
{
temp=new node;
temp->data=d;
temp->left=NULL;
temp->right=NULL;

return temp;
}

node* insert(node* cur,int key)


{
// If the tree is empty, return a new node
if (cur == NULL) return newNode(key);
// Otherwise, recur down the tree
if (key < cur->data)
cur->left = insert(cur->left, key);
else if (key > cur->data)
cur->right = insert(cur->right, key);

// return the (unchanged) node pointer


return cur;
}

void inorder(node* cur)


{
if(cur!=NULL)
{
inorder(cur->left);
cout<<cur->data<<endl;
inorder(cur->right);
}
}

void preorder(node* cur)


{
if(cur!=NULL)
{
cout<<cur->data<<endl;
inorder(cur->left);
inorder(cur->right);
}
}

void postorder(node* cur)


{
if(cur!=NULL)
{
inorder(cur->left);
inorder(cur->right);
cout<<cur->data<<endl;
}
}

node* minValue(node* cur)


{
node* current = cur;

// loop down to find the leftmost leaf


while (current!= NULL && current->left != NULL)
current = current->left;

return current;
}

node* Delete(node* cur,int data)


{
if(cur==NULL) return cur;
else if(data < cur->data) cur->left = Delete(cur->left,data);
else if(data > cur->data) cur->right = Delete(cur->right,data);

else
{
//case 1: no child
if(cur->left == NULL && cur->right == NULL)
{
delete cur;
cur=NULL;
}
//case 2: 1 child
else if(cur->left == NULL)
{
temp=cur;
cur=cur->right;
delete temp;
}
else if(cur->right == NULL)
{
temp=cur;
cur=cur->left;
delete temp;
}
//case 3: 2 or more child
else
{
temp=minValue(cur->right);
cur->data=temp->data;
cur->right=Delete(cur->right,temp->data);
}
return cur;
}
}

node* search(node* cur, int key)


{
// Base Cases: root is null or key is present at root
if (cur == NULL || cur->data == key)
return cur;
// Key is greater than root's key
if (cur->data < key)
return search(cur->right, key);

// Key is smaller than root's key


return search(cur->left, key);
}
};
main()
{
tree obj;
node* root=NULL;
node* temp;

//for getting address of first or root node


root=obj.insert(root,10);

//these nodes will be linked automatically with the root


obj.insert(root,20);
obj.insert(root,8);
obj.insert(root,7);
obj.insert(root,9);

//traversal
obj.inorder(root);
cout<<endl;
obj.Delete(root,8);
//search
int n;
cin>>n;
temp=obj.search(root,n);
if(temp!=NULL)
cout<<"Value found!";
else
cout<<"Value not found!";

You might also like