How to make my method return a list instead of strings?

    def preorder(self):
        if self.root != None:
            self._preorder(self.root)

    def _preorder(self, cur_node):
        lyst = []
        if cur_node != None:
            lyst.append(str(cur_node.data))
        #print(str(cur_node.data))
            lyst += self._preorder(cur_node.left_child)
            lyst += self._preorder(cur_node.right_child)
        return lyst

So i have this preorder method that would just print out a bunch of strings of numbers on the terminal, for example like this:

277
291
295
385
317
309
301
306
313
314
362
351
328
321
325
323
343
335
334
342
346
344
345
347
361
355
357
378
377
390
399

However I am wanting it to be a list instead. So I made a empty list, and tried appending it, and also extending it to the recursive calls. However, this is still returning None. What exactly am i missing here?

Upvotes: 0

Views: 52

Answers (1)

Samwise
Samwise

Reputation: 71444

Your _preorder function returns a list, but your preorder function doesn't do anything with it.

def preorder(self):
    if self.root != None:
        self._preorder(self.root)  # nothing is done with this value
    # end of function -- no return so we return None

You could change this to:

def preorder(self):
    return self._preorder(self.root)

and now the caller of preorder will get a list as a return value. Since _preorder handles the None case by returning an empty list it seems like preorder should just call it unconditionally.

Upvotes: 1

Related Questions