Reputation: 29
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.
Upvotes: 3
Views: 65
Reputation: 393781
call printInorder (node 50) // root
call printInorder (40) // left child of 50
call printInorder (20) // left child of 40
call printInorder (null) // left child of 20
print 20
call printInorder (null) // right child of 20
print 40
call printInorder (45) // right child of 40
call printInorder (43) // left child of 45
call printInorder (null) // left child of 43
print 43
call printInorder (null) // right child of 43
print 45
call printInorder (47) // right child of 45
call printInorder (null) // left child of 47
print 47
call printInorder (null) // right child of 47
print 50
call printInorder (60) // right child of 50
...
and so on
Upvotes: 1
Reputation: 65813
My understanding of the code is that it would recursively call printInorder(node.left) until it reached 20.
Correct.
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 ...
This is where you have missed a crucial point.
It doesn't return back to the printInOrder(node.right)
it returns back to printInOrder(40){ ... System.out.println(node.data); ...}
followed by printInOrder(40){ ... printInOrder(node.right); ...}
.
Upvotes: 0
Reputation: 7071
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...
Upvotes: 3