I was trying to understand implementation of Binary Tree traversal (PreOrder). The non recursive approach was fine, but I am totally lost while trying to understand the recursive approach.
Code :
def preorder_print(self, start, traversal): """Root->Left->Right"""
if start:
traversal += (str(start.value) + "-")
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
Binary Tree
8
/ \
4 5
/ \ \
2 1 6
My understanding is while reaching Node 2(8-4-2), left of that node 2 is None. So if start: condition would fail.
Below are my questions.
- After node2.left is None, how node2.right is traversed? (because if start: condition fails)
- After node1, how the logic moves to node5 which rootNode.right?
My understanding on recursion is poor, kindly help!
if startfails, you're nested three calls deep. You'll return back to the instance that called you. If you add some debug print statements, it may become clear. It would help even more to add a "depth" parameter and pass "depth+1" in the recursive calls. Then you'd see that the fail at "depth=3" just goes back to the call where "depth=2" and continues.preorder_printfor the left (which immediately returns), then it callspreorder_printfor the right (which immediately returns), then it exits back to the next level up, which was the "4" node.