n != 0. will work in this function, but I can now see that 0 < n is far more foolproof because you can land on the range of 0 - n and still satisfy the condition, where with the previous way I was having problems with negative numbers causing an infinite loop.
const would prevent any direct or indirect modifications of the data.
print_InOrder_private(node* Ptr) is part of a class, I have a public function called
print_InOrder(){
print_InOrder_private(root);
}
It's a little verbose but I didn't want to have to pass node* root = nullptr; to it every time I called it.
I also had not realized that I could consolidate the two if statements, so thanks for the tip.
this was extremely helpful, this made me realize why my n value was bouncing all over the place.
Was it because n was getting copied multiple times when I was passing by value and passing by reference it was just pointing back to the original value?
Thank you, this also helped me realize something on my assembly language project too.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
void BST::BST::print_InOrder_private(node* Ptr, int &n){
if(Ptr == nullptr){
if(Ptr == root)
cout <<"Tree is Empty Yo!";
return;
}
print_InOrder_private(Ptr->left, n);
if(0 < n){
cout << Ptr->key <<" ";
n--;
}
print_InOrder_private(Ptr->right, n);
}
|
so here it is, and it works great.
*Edit << added &n pass by reference