Alright, I also fixed that one and all seems to work.
By the way, I want to understand better what
was going on, and figure out what was the thing that didn't make my function work as expected.
When the RemoveNodePrivate() was called, keyNode was just a pointer to the node to be deleted.
Let's pretend we have the following tree:
1 2 3
|
[5]
[3] [7]
[1] [6] [8]
|
And let's say we pass in the pointer to the node
7.
Since 7 has two children, the
CASE 3 is chosen.
In that if-statement block, the pointer called 'smallest' will point to the node
8.
After that, I change the value-pointed by keyNode from 7 to 8.
So far, so good the changes have effect,
now our tree looks like:
1 2 3
|
[5]
[3] [8]
[1] [6] [8]
|
Now, we need to delete the "old" 8 node were we have stolen the value from
Another recursive call to RemoveNodePrivate() is launched, but this time with a pointer to the node 'smallest' (which points to the "old" 8).
Hence, keyNode this time points to the old 8.
Since the old 8 has no children,
the first case is chosen.
The node gets freed from the Heap, so the node
NO LONGER EXISTS.
FINE! IT'S EXACTLY WHAT WE WANTED, ISN'T IT?
Finally, the keyNode pointer is set to nullptr,
BUT THIS IS USELESS SINCE keyNode IS A COPY.
So, at the end of the day, the only thing that was wrong with the old code was to set a local pointer to null.
AND HERE'S THE QUESTION:
How does setting a local pointer to nullptr (instead of the original one) make the difference?
Mentioning myself
The node gets freed from the Heap, so the node NO LONGER EXISTS.
FINE! IT'S EXACTLY WHAT WE WANTED, ISN'T IT? |
So we did it! We deleted the node! What's the purpose of setting the original pointer to null?