-
binary trees
Hi there all. We are doing binary search trees. I'm having a little bit of trouble here though. Okay I need to as a few questions though.
here is the code observe
Code:
#include <iostream>
using namespace std;
struct node
{
int info;
node *left;
node *right;
};
node *root=new(node); //why declare root as a new node?
inorder(node); //is this the correct syntax for declaring the function?
insert(node *p, int x); //for user defined functions using pointers?
void insert(node *&p, int x)
{
if(p==NULL)
{
p=new(node); //if root has been declared why make a
p->info=x; //a new node in the insert function
p->left=NULL;
p->right=NULL;
}
else if(x < p->info)
{
insert(p->left, x);
}
else insert(p->right, x);
void inorder(node *p)
{
if(p!=NULL)
{
inorder(p->left);
cout<<p->info;
inorder(p->right);
}
}
void main()
{
insert(root);
}
}
with all of that being said what do you think I can do with this to make these functions run correctly
-
Got a few problems at least you should take care of:
Code:
#include <iostream>
using namespace std;
struct node
{
int info;
node *left;
node *right;
};
//The line below should be in main and you should probably
//not be allocating memory for a new node at this point,
//that will be done in the insert function, you
//should just set it to NULL in main
node *root=new(node); //why declare root as a new node?
// Forgot to add the return types for the two functions below
void inorder(node *p); //is this the correct syntax for declaring the function?
void insert(node *p, int x); //for user defined functions using pointers?
void insert(node *&p, int x) // This differs from the function prototype you provided above
{
if(p==NULL)
{
p=new(node); //if root has been declared why make a
p->info=x; //a new node in the insert function
p->left=NULL;
p->right=NULL;
}
else if(x < p->info)
{
insert(p->left, x);
}
else insert(p->right, x);
} // You were missing an ending bracket, add this
void inorder(node *p)
{
if(p!=NULL)
{
inorder(p->left);
cout<<p->info;
inorder(p->right);
}
}
void main() // main should always return an int
{
insert(root); // Your insert function takes two parameters but you only provide one
}
} // Delete this
[edit]Found a small error I missed the first time around, change is in blue above[/edit]