I have implemented binary search tree. My code is pretty simple.
struct Tree{
Tree* left;
Tree* right;
int value;
};
Here i declared basic struct.
Tree* makenode(int val){
Tree* tmp= new Tree;
tmp->left=tmp->right=NULL;
tmp->value=val;
return tmp;
}
The function that creates another struct type Tree.
void setLeft(Tree* x,int val){
x->left=makenode(val);
}
void setRight(Tree* x,int val){
x->right=makenode(val);
}
void insertt(Tree *x,int val){
while(1){
if(val < x->value){
if(x->left!=NULL){
x=x->left;
}else{
setLeft(x,val);
break;
}
}else{
if(x->right!=NULL){
x=x->right;
}else{
setRight(x,val);
break;
}
}
}
}
Loop throught the Tree and insert the value at the right place = sorting the tree while adding to it.
What is making trouble to me is this little function
void travel(Tree *x){
if(x->left!=NULL){
travel(x->left);
}
Tree *b;
b=x->right;
if(x->value == b->value){
cout << "Duplicate is " << x->value << endl;
return ;
}
cout << "Value is " << x->value << endl;
if(x->right!=NULL){
travel(x->right);
}
}
It nicely prints values if i omit
Tree *b;
b=x->right;
if(x->value == b->value){
cout << "Duplicate is " << x->value << endl;
return ;
}
I want it to check the enxt value when its printing current value , it both are the same = we have duplicit. But it always crash my program. What is causing this? The sorting works , the only problem that could be here is behavior of recursion ,but i cant figure out what
I tried to remake it as
void travel(Tree *x, vector<int> &y){
vector<int>::iterator it;
if(x->left!=NULL){
if( x->value == x -> left -> value){
it=find( y.begin(), y.end(), x->value );
if(it==y.end()){
y.push_back(x->value);
}
}
travel(x->left, y);
}
cout << "Value is " << x->value << endl;
if(x->right!=NULL){
if( x->value == x -> right -> value){
it=find( y.begin(), y.end(), x->value );
if(it==y.end()){
y.push_back(x->value);
}
}
travel(x->right,y);
}
}
But with this main function
int main()
{
vector<int> dups;
Tree * node = makenode(55);
insertt(node,99);
insertt(node,5);
insertt(node,99);
insertt(node,100);
insertt(node,13);
insertt(node,99);
insertt(node,55);
travel(node,dups);
printDup(dups);
return 0;
}
and printDup
using namespace std;
void printDup( vector<int> &y){
cout << "Duplicates are: ";
for( int i = 0; i < y.size(); i++){
cout << y[i] << " ";
}
}
It only prints 99 , why doesnt the others values get pushed into vector? Also how could i remakte the travel function make more elegant?
std::maporstd::multimapcould greatly simplify as well as improve your code). For example, your entire could could be easily replaced with this.