Got help from Martyr2's Programming Underground > Plant a Node, make a Binary Tree Forest in C++!
Well here is the code
#include <iostream>
#include <ctime>
using namespace std;
class Btree{
int num;
Btree *right;
Btree *left;
public:
void addItem(Btree *&tree, int val);
void printTree(Btree *aTree);
};
void Btree::addItem(Btree *&tree, int val){
Btree *temp=new Btree;
Btree *ttemp=tree;
temp->num=val;
temp->left=NULL;
temp->right=NULL;
bool flag = false;
if(tree==NULL)
tree=temp;
else{
while(!flag){
if(val<ttemp->num){
if(ttemp->left==NULL){
ttemp->left=temp;
flag=true;
}else{
ttemp=ttemp->left;
}
}else
if(val>ttemp->num){
if(ttemp->right==NULL){
ttemp->right=temp;
flag=true;
}else
ttemp=ttemp->right;
}else
flag=true;
}
}
}
void Btree::printTree(Btree *aTree){
if(aTree->left!=NULL)
printTree(aTree->left);
cout<<aTree->num<<endl;
if(aTree->right!=NULL)
printTree(aTree->right);
}
int main(){
int num=0;
Btree *root=NULL;
srand((unsigned int)time(NULL));
for(int i=0;i<20;i++){
num=rand()%100+1;
root->addItem(root,num);
}
root->printTree(root);
cin.get();
return 0;
}
All comments are welcome

New Topic/Question
Reply




MultiQuote




|