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
|
#include<iostream>
using namespace std;
class btree
{
public:
struct node
{
node *left;
int data;
node *right;
};
node *root;
btree();
void insert(node*,int);
void inorder(node*);
void postorder(node*);
void preorder(node*);
void del(node*);
node* find(node*,int);
};
btree::btree()
{
root=NULL;
}
btree::node* btree::find(node *temp, int item)
{
if(temp==NULL)
return temp;
else if(temp->data<item)
{
if(temp->right!=NULL)
return find(temp->right,item);
}
else
{
if(temp->left!=NULL)
return find(temp->left,item);
}
return temp;
}
void btree:: insert(node *temp, int item)
{
node *place=find(temp,item);
if(place==NULL)
{
temp=new node;
temp->data=item;
temp->right=NULL;
temp->left=NULL;
root=temp;
}
else if(item<place->data)
{
place->left=new node;
place->left->data=item;
place->left->left=NULL;
place->left->right=NULL;
}
else if(item>place->data)
{
place->right=new node;
place->right->data=item;
place->right->left=NULL;
place->right->right=NULL;
}
}
void btree::inorder(node *temp)
{
if(temp==NULL)
return;
else
{
inorder(temp->left);
cout<<temp->data<<" ";
inorder(temp->right);
}
}
void btree::preorder(node *temp)
{
if(temp==NULL)
return;
else
{
cout<<temp->data<<" ";
preorder(temp->left);
preorder(temp->right);
}
}
void btree::postorder(node *temp)
{
if(temp==NULL)
return;
else
{
postorder(temp->left);
postorder(temp->right);
cout<<temp->data<<" ";
}
}
int main()
{
btree a;
a.insert(a.root,9);
a.insert(a.root,3);
a.insert(a.root,6);
a.insert(a.root,1);
a.insert(a.root,8);
a.insert(a.root,2);
a.insert(a.root,5);
a.insert(a.root,7);
a.insert(a.root,4);
a.insert(a.root,10);
a.inorder(a.root);
cout<<endl;
a.preorder(a.root);
cout<<endl;
a.postorder(a.root);
cout<<endl;
system("pause");
return 0;
}
|