-
Recursion
I'm trying to get my binary tree to print out 10 things per line. I'm having issues though, as when the traversing reaches a leaf, on moving to the next printable node my counter is reset to one more than that node's parent, which isn't what I want. I'm not sure how to correct this?
Here's the functions I'm using
Code:
void BinarySortTree::print_preorder()
{
int n = 0;
cout << "Preorder: \n";
preorder(Root, n);
cout << "\n\n";
}//print_preorder
Code:
void BinarySortTree::preorder(tree_node* p, int numprint) {
if(p != NULL) {
numprint++;
cout << numprint;
cout<< p->data<<" ";
preorder(p->left, numprint);
preorder(p->right, numprint);
}//if
else return;
}//preorder
I've moved numprint around a few places, but am not getting the result I wanted.
I initially planned on just doing preorder(p->right/left, numprint++) and the first part of the print_preorder having an if statement saying if (numprint % 10 == 0) cout << endl;
Seemed simple enough, but doesn't work :( I haven't used recursion a whole lot, can you help?
-
So when the first recursive call to preorder is made, that call and all its sub-calls alter their local copy of the numprint variable. Then after they return you pass the same value that you passed to that recursive call into the second recursive call.
Two obvious solutions come to mind, both involve changing the function signature in some way.
-
I tried last night, and it seems to me that you're alluding to using a pointer of sorts, so that I'm incrementing what is at a memory location? I haven't been able to properly implement it though.
-
I wouldn't use a pointer.
The second preorder's numprint needs to depend on the number of nodes in the first preorder's branch. So I'd make preorder return the number of nodes.
-
I was thinking more along the lines of reference rather than pointer, but either would work.
And King Mir has the other solution.