binary search tree print function: Logic not clear-help

Hello. Pls explain to me

1) how come root node is printed when the first call to function goes to left subtree?

2) How it resets to root to go to right subtree from last left tree leaf?

1
2
3
4
5
6
7
8
9
10
11
void bst:: printNodes(hwareItem*& root){

    if(root){
        printNodes(root->left);
        cout<<root->barcode<<endl;
        cout<<root->description<<endl;
        cout<<root->price_per_unit<<endl;
        cout<<root->stock<<endl;
        printNodes(root->right);}

}
I don't get you. This uses recursion(calling a function from itself)

Aceix.
Last edited on
The code looks fine to me. If the results aren't what you expect then maybe the structure of the tree isn't what you think?

2) How it resets to root to go to right subtree from last left tree leaf?

The beauty of recursion is that each call has different parameters (and local variables). So you don't need to "reset to root": when you return from a lower call, the previous value of root is there unchanged. Actually, to express this better in your code, don't make root a reference, and call it subtree:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void bst:: printNodes(hwareItem* subtree){

    if(subtree){
        printNodes(subtree->left);

        cout<< subtree->barcode << '\n';
        cout<< subtree->description << '\n';
        cout<< subtree->price_per_unit<< '\n';
        cout<< subtree->stock <<endl;

        printNodes(subtree->right);
   }

}


I've also replaced all but the last endl with '\n'. This will speed up the output y not flushing so frequently.
Registered users can post here. Sign in or register to post.