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.
My understanding on recursion is poor, kindly help!
Watch this, see if this helps:
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def addleft(self,value):
self.left = Node(value)
def addright(self,value):
self.right = Node(value)
def preorder_print(self, start, traversal='', depth=0):
print( " "*depth, start.value if start else "None" )
if start:
traversal += (str(start.value) + "-")
print(' '*depth, "check left")
traversal = self.preorder_print(start.left, traversal, depth+1)
print(' '*depth, "check right")
traversal = self.preorder_print(start.right, traversal, depth+1)
return traversal
base = Node(8)
base.addleft(4)
base.left.addleft(2)
base.left.addright(1)
base.addright(5)
base.right.addright(6)
print( base.preorder_print( base ) )
Output:
8
check left
4
check left
2
check left
None
check right
None
check right
1
check left
None
check right
None
check right
5
check left
None
check right
6
check left
None
check right
None
8-4-2-1-5-6-