A friend and I did the Inorder-tree-walk with pen and paper. We both can't figure out how the algorithm would move 'up' the tree again upon hitting a leaf:
We are using the algorithm as described by our professor and taken from "Introduction to Algorithms, Third Edition" Chapter 12 page 288:
Inorder-tw(node)
if node != nil
Inorder-tw(node.left)
print node.key
Inorder-tw(node.right)
- To visualize what we did on paper I wrote each "round" as {1; <key_of_node>}
- To understand our thought process you should read all the {1; ..}'s first, then all the {2; ...}'s and so on
- We are stuck when we hit the node with the key 11 where both;
node.left
andnode.right == nil
- This is exactly the point were we don't understand how the algorithm is able to be called again with a the node of the key 17
- We know that the answer is [11,17,18,31,47,57,69,78,81]
47 Inorder-tw(node): {1; 47} {2; 18} {3;17} {3; 11} {5; nil}
/ \ if node != nil: {1; T} {2; T} {3; T} {4; T} {5; F} node=nil 11.right
/ \ Inorder-tw(node.left): {1; 18} {2;17} {3;11} {4; nil}
18 78 print node.key {4; 11}
/\ /\ Inorder-tw(node.right) {4; nil}
/ \ / \
17 31 57 81
/ \
/ \
11 69
The example was take from here
Though the examples are nicely visualizing what happens in each step, they don't show us how the input is "changed" in the recursive call upon hitting any leaf. As in my head we are stuck forever at node with the key 11 that returns children of the value == nil
.
Writing out the calls as I understand them it would be:
Inorder-tw(47) Inorder-tw(18) Inorder-tw(17) Inorder-tw(11) Inorder-tw(Nil)
47 != Nil -> True 18 != Nil -> T 17 != Nil -> T 11 != Nil -> T Nil != Nil FALSE
Inorder-tw(47.left) Inorder-tw(18.left) Inorder-tw(17.left) Inorder-tw(11.left)
I can't understand how the algorithm is supposed to print
even though the if statement is evaluated as FALSE
.
Can anyone explain how the algorithm manages to move back up the tree by changing the input in the recursive call upon hitting a leaf?