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 125 126 127 128 129 130 131 132 133 134 135 136 137 138
|
#include <iostream>
#include <string.h>
#include <conio.h>
using namespace std;
template <class object>
class Tree{
public:
Tree(object * ob)
{
obj = ob;
Left = Right = NULL;
}
Tree()
{
obj = NULL;
Left = Right = NULL;
}
void set_obj(object * objt){objt = obj;};
object * get_obj(){return obj;};
void set_left(Tree * left){Left = left;};
void set_right(Tree * right){Right = right;};
Tree * get_left(){return Left;};
Tree * get_right(){return Right;};
private:
object * obj;
Tree * Left;
Tree * Right;
};
void preorder(Tree<char>*);
void inorder(Tree<char>*);
void postorder(Tree<char>*);
void insert(Tree<char>*,char*);
int main(int argc, char* argv[])
{
Tree<char> * ROOT = new Tree<char>();
static char* x[] = {"Sarmad","Usman","Rahman","Ali","Asgar","Zibra","Qamar",NULL};
ROOT->set_obj(x[0]);
for(int i=1; i<2;i++)
{
insert(ROOT,x[i]);
}
cout<<"PRE-ORDER"<<endl;
preorder(ROOT);
cout<<'\n'<<endl;
cout<<"In-ORDER"<<endl;
inorder(ROOT);
cout<<'\n'<<endl;
cout<<"POST-ORDER"<<endl;
postorder(ROOT);
_getch();
}
void preorder(Tree<char>* Node)
{
if(Node != NULL)
{
cout<<*(Node->get_obj())<<'\t';
preorder(Node->get_left());
preorder(Node->get_right());
}
}
void inorder(Tree<char>* Node)
{
if(Node != NULL)
{
inorder(Node->get_left());
cout<<*(Node->get_obj())<<'\t';
inorder(Node->get_right());
}
}
void postorder(Tree<char>* Node)
{
if(Node != NULL)
{
postorder(Node->get_left());
postorder(Node->get_right());
cout<<*(Node->get_obj())<<'\t';
}
}
void insert(Tree<char>* Root,char * info)
{
Tree<char> * Node = new Tree<char>(info);
Tree<char>* p,*q;
p = q = Root;
while(strcmp(p->get_obj(),info) != 0 && q != NULL)
{
p = q;
if(strcmp(p->get_obj(),info) < 0)
{
q = p->get_left();
}
else
{
q = p->get_right();
}
}
if(strcmp(p->get_obj(),info) == 0)
{
cout<<"Number Dublicated"<<*(info)<<endl;
delete Node;
}
else if(strcmp(p->get_obj(),info)< 0)
{
p->set_left(Node);
}
else
{
p->set_right(Node);
}
}
|