Problem entering values into a binary search tree
Nov 25, 2013 at 6:08am UTC
Hey guys! I'm working on a binary search tree for class, and I'm getting stuck at the very beginning. When I try to add a value to the tree, it seems to simply ignore the line to add it. I've been beating my head against the wall for a few hours now, and I thought I'd look for some outside help. There's a bunch of print statements here just to help me find out where the problem is, so they won't be in the final product.
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
void tree::add(int x, node* y)
{
cout << "running from start" << endl;
if (root == NULL)
{
root = new node(x);
cout << "added to tree" << endl;
return ;
//cout << root->print() << endl;
}
else
{
cout << "running else loop" << endl;
if (y == NULL)
{
cout << "adding value" << endl;
y = new node(x);
cout <<"added value" << endl;
return ;
}
else if (x == y->values())
{
cout << "Error! This value is already in the binary tree" << endl;
return ;
}
else if (x < y->values())
{
cout << " cycling for less than" << endl;
add (x, y->findleft());
}
else if (x > y->values())
{
cout << " cycling for more than" << endl;
add (x, y->findright());
}
cout << "got too far" << endl;
}
}
Here's the header files as well
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include "node.h"
class tree{
private :
node* head;
node* tail;
node* now;
node* root;
int nodes;
public :
tree();
node* findroot();
void add(int , node*);
void Delete(int );
void Search();
void inorder(node*);
void height();
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Node.h
class node{
private :
int value;
node* left;
node* right;
public :
node (int );
int values();
int print();
node* findleft();
node* findright();
node* addnode();
};
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
node.cpp
#include "node.h"
#include <iostream>
node::node(int x)
{
value = x;
right = NULL;
left = NULL;
}
int node::print ()
{
return value;
}
node* node::findleft ()
{
return left;
}
node* node::findright()
{
return right;
}
int node::values()
{
return value;
}
Last edited on Nov 25, 2013 at 6:11am UTC
Topic archived. No new replies allowed.