I’m working on a programming assignment and writing a bunch of functions to implement a binary search tree, and some functions are given. I thought I understood recursion, but I keep getting hung up on switching directions, if you will.
Here is a function given with the assignment:
static void deleteAll(BSTNode<Data>* n) {
if (0 == n) return;
deleteAll(n->left);
deleteAll(n->right);
delete n;
}
To delete a really short tree,
root / \ lefty righty
I call deleteAll(root). n != 0 so now I call deleteAll(lefty). n != 0 so I call deleteAll(lefty->left). There is no left node of course. When I added the lefty node my constructor initialized the left, right, and parent pointers to 0, so now n == 0. So I return out of the function and never delete righty. How do I ever get to deleteAll(n->right)?
As I said, this function is provided so I’m not supposed to change it. I thought maybe I have to call deleteAll(b.begin()) or b.end() to start with either the left- or rightmost node, but every time I go through it in my mind I hit n == 0.
Please help me understand.
Imagine an arrow pointing to the current line that is being executed. When we call
deleteAll(root), first we check ifrootis 0:Because
root != 0, we then calldeleteAll(root->left):Now the arrow will move back up to the top of the function and start doing the same for
lefty, running through the lines 1-4 in my comment (at line 2, the same expansion will happen again, until a null node is found). But the important thing here is that it remembers where it was before the function call so that it can resume later. SodeleteAll(root->left)will go and do what it does and eventually returns. Then the original call continues:Now the right node is deleted too. This happens at every step of the recursion. Remember that
returnonly returns out of the current function, not the entire recursive chain.