Here's the complete class definition I'm tinkering with:
Code:
class node
{
int data;
node* left = NULL; // causes error here after I inserted the NULL per dragon's instructions
node* right = NULL; // ditto
public:
int lookup(node*, int);
void insert(node*, int);
void set(int i){data = i;}
};
int node::lookup(node* n, int target)
{
if(n==NULL) // the execution just bypasses this conditional even when n is unitialized.
{
return(false);
}
else
{
if(n->data == target) return(true);
{
if(n->data > target) lookup(n->right, target);
else lookup(n->left, target);
}
}
}
void node::insert(node* n, int input)
{
if(n == NULL)
{
n = new node;
data = input;
}
if(input > n->data)
{
insert(n->right, input);
}
else
{
insert(n->left, input);
}
}
This is actually the modification of a bit of code in a tutorial I got on the internet:
Code:
struct node {
int data;
struct node* left;
struct node* right;
};
static int lookup(struct node* n, int target) {
// 1. Base case == empty tree
// in that case, the target is not found so return false
if (n == NULL) {
return(false);
}
else {
// 2. see if found here
if (target == n->data) return(true);
else {
// 3. otherwise recur down the correct subtree
if (target < n->data) return(lookup(n->left, target));
else return(lookup(n->right, target));
}
}
}
struct node* NewNode(int data) {
struct node* n = new(struct node); // "new" is like "malloc"
n->data = data;
n->left = NULL;
n->right = NULL;
return(n);
}
struct node* insert(struct node* n, int data) {
// 1. If the tree is empty, return a new, single node
if (n == NULL) {
return(NewNode(data));
}
else {
// 2. Otherwise, recur down the tree
if (data <= n->data) n->left = insert(n->left, data);
else n->right = insert(n->right, data);
return(n); // return the (unchanged) node pointer
}
}
So at the moment, I have no idea whether my modification is fundamentally wrong or not because I can't even get it to work with the conditional. (BTW, I'm using VC++ 2003)