I am currently studying Binary trees. I came across this very efficient code for traversing through the tree ( in the example this is an in order traversal ). It uses recursion, which as a concept I understand. However I cannot seem to get my head around how this actually works. The main thing i am confused about is how does it go up the list each time so that start.left isn’t always the same number. Could someone please give a step by step of how this actually traverses up the tree. Thanks in advance
Edited To add clarity to question:
- I understand if start is not None, then start.left gets added to the recursion call of the same function.
- With each recursion, variable traversal being assigned to the return of the function.
- When start is eventually None ( the traversal has completed ) the function returns the traversal element, and continues the process.
Where my confusion is, is that i cannot seem to find where the code, ‘knows’ that its traversed to 4, and now the next element to return is 2. Where is the mechanism, that now stops at 2 and returns it, and so on?
class Node():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __str__(self):
return str(self.data)
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
def inorder_print(self, start, traversal):
"""Left -> root -> right"""
if start:
traversal = self.inorder_print(start.left, traversal)
traversal += (str(start.data) + "-")
traversal = self.inorder_print(start.right, traversal)
return traversal
tree = BinaryTree(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
tree.root.right.right.right = Node(8)
print(tree.inorder_print(tree.root, ""))