samedi 11 avril 2020

Recursive Pre-order Binary Tree Traversal in Python - Nonetype Error

I am having issues with a helper method in my code. I providing both correct and incorrect approaches to the problem but I fail to see the difference between the two.

My approach :

def preorder_print(self, start, traversal):
        if start == None:
            return traversal
        else:
            traversal += str(start.value)
            traversal = self.preorder_print(start.left,traversal)
            traversal = self.preorder_print(start.right,traversal)

Note : start is the root node and traversal is an empty string

This gives TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'

The correct approach :

def preorder_print(self, start, traversal):
        if start:
            traversal += str(start.value) 
            traversal = self.preorder_print(start.left, traversal)
            traversal = self.preorder_print(start.right, traversal)
        return traversal

I am unable to understand the difference between these two approaches. Can someone explain how the two approaches differ in execution.

Aucun commentaire:

Enregistrer un commentaire