Binary Search Tree

Hi everybody. I make logical mistake but I don't find mistake.

my algorithm;

#include<iostream>

using namespace std;

struct node{
struct node *left;
struct node *right;
int data;
};

void add(node *p,int sayi){

if(p==NULL){
p=new node();
p->data=sayi;
p->left=NULL;
p->right=NULL;
}
else{
if(p->data>sayi)
{
if(p->left==NULL)
p->data=sayi;
else
add(p->left,sayi);
}
else{
if(p->right==NULL)
p->data=sayi;
else
add(p->right,sayi);
}
}
cout<<"sayi ="<<p->data;

}

void postorder(node *p){
if(p!=NULL)
{

if(p->left!=NULL)
postorder(p->left);
if(p->right!=NULL)
postorder(p->right);
cout<< p->data<<endl;
}
else{
cout<<"hata"<<endl;

}
}
void main(){
struct node *p =NULL;
int sayi=0;

while(sayi!=-1){
cout<<"Bir sayi giriniz...";
cin>>sayi;
add(p,sayi);

postorder(p);
}

system("pause");
}

Thanks ;)
If you find that you need to change a parameter which is a pointer in the body of a function, and that change should be reflected in the original pointer, you need to pass the parameter by reference or by a pointer to the type you want to change.

In other words, the prototype for add() should look like:

void add(node *& p,int sayi)

or

void add(node ** p,int sayi){

I would suggest the former, since the syntax within the function tends to be less confusing.

1
2
3
4
5
6
7
        if(p->data > sayi)
        {
            if(p->left==NULL)
                p->data=sayi;
            else
                add(p->left,sayi);
        }


Does this code make sense to you? If data in the current node is greater than the data we're adding and left is NULL, replace the current node's data with the data to be added?

[Edit: Use code tags in the future, it makes your code much easier to read. Find the <> button.]
Last edited on
Topic archived. No new replies allowed.