help with a garbage value

A

andrew browning

this program is a binary tree using nodes. it should do an in-order
print, which it does. however, it inserts a garbage value at the end
of the print. ex: cin >> 1 2 3 4 5 prints 1 2 3 4 5 7884788. can
anyone help? value_type is an integer.

constructors:

tree():data(value_type()),left(NULL), right(NULL){}

tree(value_type vt, tree* l = NULL, tree* r = NULL):
data(vt), left(l), right(r) {};

insert function:

tree::tree* tree::insert(tree* node, value_type data){
if (node == NULL){
return(new tree(data));
}else

if(data <= node->data){
node->left = insert(node->left, data);
}else
if(data >= node->data){
node->right = insert(node->right, data);
}
return node;
}


driver:

int main(){

tree t1;
int user_input;
tree* tree_ptr = new tree(user_input);


while(cin >> user_input && cin.peek() != EOF){
t1.insert(tree_ptr, user_input);
}
t1.inorder_print(tree_ptr);



return 0;

}
 
R

Rolf Magnus

andrew said:
this program is a binary tree using nodes. it should do an in-order
print, which it does. however, it inserts a garbage value at the end
of the print. ex: cin >> 1 2 3 4 5 prints 1 2 3 4 5 7884788. can
anyone help? value_type is an integer.

constructors:

tree():data(value_type()),left(NULL), right(NULL){}

tree(value_type vt, tree* l = NULL, tree* r = NULL):
data(vt), left(l), right(r) {};

Just my opinion:
There is no significant limit to the number of lines you can use in a
program. You could increase readability by not putting everything in as few
lines as possible.
insert function:

tree::tree* tree::insert(tree* node, value_type data){
if (node == NULL){
return(new tree(data));
}else

if(data <= node->data){
node->left = insert(node->left, data);
}else
if(data >= node->data){
node->right = insert(node->right, data);
}
return node;
}


driver:

int main(){

tree t1;
int user_input;
tree* tree_ptr = new tree(user_input);


while(cin >> user_input && cin.peek() != EOF){

Replace that with:

while(cin >> user_input){
t1.insert(tree_ptr, user_input);
}
t1.inorder_print(tree_ptr);



return 0;

}


And where is your inorder_print() implementation?
 
A

andrew browning

Rolf Magnus wrote: And where is your inorder_print() implementation? :

void inorder_print(tree* node_ptr){
if(node_ptr != 0){
inorder_print(node_ptr->get_left());
std::cout << node_ptr ->get_data() << std::endl;
inorder_print(node_ptr->get_right());

i changed the driver as you recommended but i get a 0 at the begining
of the output. as for the readability, i will keep that in mind when
asking other people to read it:)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,222
Members
46,810
Latest member
Kassie0918

Latest Threads

Top