BST Inorder traversal
May 21, 2012 at 5:27pm UTC
Hi, can someone explain me how to output content of BST in Inorder traversal ?
I need this for the assignment, just spend whole night writing BST and i just cant understand how to output it correctly, I am going to post my code below, please write the code for output(as simple as possible please because I am just starting with c++ ) thank you.
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
//content of header
#include <iostream>
using namespace std;
struct node
{
int bribe;
node *left;
node *right;
};
class Tree
{
private :
node *root;
void AddItem(node *&,int );
void AppendLeft(node *&,int );
void AppendRight(node *&,int );
public :
Tree(){root=NULL;}
void add();
};
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
//content of header.cpp
#include "training.h"
void Tree::add()
{
int aBribe;
cout<< "Enter the person's contribution: " ;
cin >> aBribe;
AddItem(root,aBribe);
if (root==NULL)
{
node *newNode;
newNode= new node;
newNode->bribe=aBribe;
root=newNode;
root->left=root->right=NULL;
cout<<"Added a root " <<root->bribe<<endl;
}
}
void Tree::AddItem(node *& root1,int brb)
{
node * temp;
temp=root1;
while (temp !=NULL)
{
/////////////////////////////////////
if (brb > temp->bribe)
{
if (temp->right==NULL)
AppendRight(temp,brb);
else
temp=temp->right;
}
/////////////////////////////////////
/////////////////////////////////////
else if (brb < temp->bribe)
{
if (temp->left==NULL)
AppendLeft(temp,brb);
else
temp=temp->left;
}
else
{
cout<<"Binary tree can not contain same number twice" <<endl;
temp=NULL;
}
}
}
void Tree::AppendLeft(node *& root1,int brb)
{
node *newNode;
newNode=new node;
newNode->bribe=brb;
cout<<"Added " <<brb<<" on the left side of " <<root1->bribe<<endl;
root1->left=newNode;
newNode->left=newNode->right=NULL;
root1=NULL;
}
void Tree::AppendRight(node *& root1,int brb)
{
node *newNode;
newNode=new node;
newNode->bribe=brb;
cout<<"Added " <<brb<<" on the right side of " <<root1->bribe<<endl;
root1->right=newNode;
newNode->left=newNode->right=NULL;
root1=NULL;
}
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
//test.cpp
#include "training.h"
using namespace std;
int main()
{
Tree LocalTree;
int choice;
while (3 !=0)
{
LocalTree.add();
}
return 0;
}
Topic archived. No new replies allowed.