1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
|
#include<iostream>
#include<conio.h>
using namespace std;
struct Tree
{
int data;
Tree *left;
Tree *Right;
};
Tree * root =NULL;
void insert(Tree *temp,Tree *prev ,int elm)
{
if (temp==NULL)
{
temp=new Tree;
temp->data=elm;
temp->Right=NULL;
temp->left=NULL;
if(root==NULL)
root=temp;
else
{
if(elm>=prev->data){ prev->Right=temp;}
else{prev->left=temp;}
}
}
else if(elm>=temp->data)
{insert(temp->Right,temp,elm); }
else
{insert(temp->left,temp,elm);}
}
void Inorder(Tree *temp)
{
if (temp!=NULL)
{
Inorder(temp->left);
cout<<"Temp->data : "<<temp->data<<endl;
Inorder(temp->Right);
}
}
void Postorder(Tree *temp)
{
if(temp!=NULL)
{
Postorder(temp->left);
Postorder(temp->Right);
cout<<temp->data<<endl;
}
}
void Preorder(Tree *temp)
{
if(temp!=NULL)
{
cout<<temp->data<<endl;
Preorder(temp->left);
Preorder(temp->Right);
}
}
void Min(Tree *temp)
{
if(temp->left==NULL)
cout<<"Min : "<<temp->data<<endl;
else
{
Min(temp->left);
}
}
void Max(Tree *temp)
{
if(temp->Right==NULL)
cout<<"Max :"<<temp->data<<endl;
else
Max(temp->Right);
}
Tree* getParent(Tree* curr, Tree* prev, int num)
{
if(curr->data == num)
return prev;
else if(num < curr->data)
return getParent(curr->left, curr, num);
else //if(num > curr->data)
return getParent(curr->Right, curr, num);
}
void DeleteTree(Tree* temp, int num)
{ if (temp==NULL)
cout<<"Number not Found";
else if((temp->data == num)) //Tree found
{ Tree *parent, *min ;
int number;
// if number is found at a leaf Tree
if((temp->left == NULL) && (temp->Right == NULL))
{
parent=getParent(root, root, temp->data); //will return parent Tree
if(parent->left == temp)
parent->left = NULL;
else if (parent->Right == temp)
parent->Right = NULL;
delete temp;
}
}
}
int main()
{
insert(root,root,9);
insert(root,root,11);
insert(root,root,4);
insert(root,root,3);
Min(root);
Max(root);
Inorder(root);
Tree * t=getParent(root,root,4);
cout<<"PARENT : "<<t->data<<endl;
DeleteTree(root,11);
DeleteTree(root,9);
DeleteTree(root,4);
DeleteTree(root,3);
Inorder(root);
getch();
}
|