I am working on a Red Black tree for a data structures class.
I have the code:
void printInorder(Node node) //Input is initially the root node
{
if (node == null)
{
return;
}
printInorder(node.left);
System.out.println(node.data);
printInorder(node.right);
}
Let's use this Binary tree as an example:
50
/ \
40 60
/ \ \
20 45 70
/ \ /
43 47 65
The output of the code is correct and is : 20 40 43 45 47 50 60 65 70
My understanding of the code is that it would recursively call printInorder(node.left) until it reached 20.
At that point, it would then print "20 ", then it checks printInorder(node.right), sees that it is null and returns back to the printInorder(node.right) statement, at which point it is at the bottom of the method and has no more code to run so it exits.
The output is correct, but from my understanding of the code it should stop after printing "20 ".
Can someone explain the process of this recursive loop, LITERALLY step-by-step for me? Please pretend you are explaining it to someone with a mental impediment. Thank you.
There is this joke "To understand recursion one should first understand recursion"
First lets look at the function. What does it do?
Checks if there is a left node and if there is goes there (without printing yet)
If there is no left node prints
checks if there is a right node and goes there.
So the execution here.
and so it goes...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With