I am trying to write a code, which, given a Binary Search Tree root and a level, prints out the elements of the tree at that level. This is working fine:
def myprint(root,level):
if root:
if not level:
print root.data,
else:
myprint(root.left,level-1)
myprint(root.right,level-1)
However, when I try to tweak it to print the elements at a level in reverse order, it dosn’t work. For the following tree:
26
/ \
13 39
/ \ / \
6 19 32 51
/ \ / \ / \ / \
4 8 14 31 33 68
\
17
if I want to output the elements at level 3 (level of root is 0) from right to left, the output should be 68 33 31 14 8 4. The code above does the reverse correctly, that is, prints out 4 8 14 31 33 68. But the below code doesn’t print the reverse order correctly, and prints out 31 33 68 4 8 14 instead:
def revprint(root,level):
if root:
if not level:
print root.data,
else:
myprint(root.right,level-1)
myprint(root.left,level-1)
Can anybody spot the error, and tell me how to rectify it? The code for initializing the tree is as follows:
class tree:
def __init__(self,data):
self.data = data
self.successor,self.left,self.right = None,None,None
def push(self,data):
root = self
while root:
oldroot = root
if root.data > data:
root = root.left
elif root.data < data:
root = root.right
if data > oldroot.data:
oldroot.right = tree(data)
else:
oldroot.left = tree(data)
a = tree(26)
for x in [13,39,6,19,4,8,5,10,9,14,17,15,32,51,68,31,33,36,34]:
a.push(x)
You are calling
myprintinrevprint. The fixed version ofrevprint: