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