Search code examples
pythonbinary-search-treetree-traversal

Why is my helper method not activating recursively?


I have a Binary Search Tree and I am trying to trace recursively in order through the tree and append each key,value to a list. It is only appending the first key,value to the list and not going through the list in order. I pasted my code below, along with the test code I used at the bottom. Any help on how to get past this issue is super appreciated!

class TreeMap:
    class Node:
        def __init__(self, key, value):
            self.key = key
            self.value = value
            self.left = None
            self.right = None
    def __init__(self):
        self.root = None
        self.numsearches = 0
        self.numcomparisons = 0
    def add(self, newkey, newvalue):
        newkey = newkey.lower()
        if self.root == None:
            self.root = TreeMap.Node(newkey, newvalue)
        else:
            TreeMap.add_helper(self.root, newkey, newvalue)

    def add_helper(thisnode, newkey, newvalue):
        if newkey <= thisnode.key:
            if thisnode.left == None:
                thisnode.left = TreeMap.Node(newkey, newvalue)
            else:
                TreeMap.add_helper(thisnode.left, newkey, newvalue)
        else:
            if thisnode.right == None:
                thisnode.right = TreeMap.Node(newkey, newvalue)
            else:
                TreeMap.add_helper(thisnode.right, newkey, newvalue)
    
    def print(self):
        TreeMap.print_helper(self.root, 0)
    def print_helper(somenode, indentlevel):
        if somenode == None:
            print(" "*(indentlevel),"---")
            return
        if not TreeMap.isleaf(somenode):
            TreeMap.print_helper(somenode.right, indentlevel + 5)
            print(" "*indentlevel + str(somenode.key) + ": " +str(somenode.value))
        if not TreeMap.isleaf(somenode):
            TreeMap.print_helper(somenode.left, indentlevel + 5)
    
    def isleaf(anode):
        return anode.left == None and anode.right == None


    def listify(self, whichorder="in"):
        '''
        Returns a list consisting of all the payloads of the tree.  (This returns a plain old Python List.)
        The order of the payloads is determined by whichorder, which defaults to inorder.
        The other possibilities are "pre" and "post".
        If the tree is empty, return the empty list.
        '''
        assert type(whichorder) is str,"Whichorder is a string, and can only be pre, in or post"
        assert whichorder in ["pre","in","post"],"Whichorder is a string, and can only be pre, in or post"
        return TreeMap.listify_helper(self.root, whichorder)

    def listify_helper(somenode, whichorder):        
        order_list = []
        if somenode == None:
            return order_list
        elif somenode != None and whichorder == 'in':
            TreeMap.listify_helper(somenode.left, 'in')
            order_list.append(somenode.key+ '='+somenode.value)
            TreeMap.listify_helper(somenode.right, 'in')
        return order_list

TEST CODE:

import treemap

translator = treemap.TreeMap()

translator.add("cat", "Katze")
translator.add("bird", "Vogel")
translator.add("dog", "Hund")
translator.add("snake", "IDK")
translator.add("bear", "IDK")
translator.add("octopus", "Tintenfisch")
translator.add("horse", "Pferd")
translator.add("zebra", "IDK")

translator.print()
print("---------------------------------------------------")

print (translator.listify())

Solution

  • The problem is here:

    def listify_helper(somenode, whichorder):        
            order_list = []
    

    This function initialises its own local order_list every time it is invoked. Pass order_list as a parameter instead so that the same list is appended to by each recursive invocation.

    Alternatively, append each element of the result of the recursive calls of listify_helper to order_list, although this approach could result in unneeded copying.