0

Given a Tree structure:

class Node:
def __init__(self, data, left=None, right=None):
    self.left = left
    self.right = right
    self.data = data

I want to be able to take the results(self.data) of the recursive calls of

def preOrder(self): 
    if self:
        print(self.data)
        if self.left is not None:
            self.left.preOrder()
        if self.right is not None:
            self.right.preOrder()

and be able to return them in a single list.

Where

root= Node(2,Node(1,Node(6),Node(3)),Node(3,None,Node(9)))
root.preOrder()

would yield [2,1,6,3,3,9].

I have tried messing around with helper function but I am stuck and haven't been able to get a working solution.

nebulaEXE
  • 1
  • 1

2 Answers2

0
class Node:
    def __init__(self, data, left=None, right=None):
        self.left = left
        self.right = right
        self.data = data
    def preOrder(self, result = None): 
        if result is None:
            result = []
        if self:
            result.append(self.data)
            if self.left is not None:
                self.left.preOrder(result)
            if self.right is not None:
                self.right.preOrder(result)
        print(result)        
        return result

root= Node(2,Node(1,Node(6),Node(3)),Node(3,None,Node(9)))
root.preOrder()

Instead of printing append to a list and send that list to the same function again. Keep appending to it and return at the end.

leoOrion
  • 1,833
  • 2
  • 26
  • 52
  • Thanks for pointing this out. Handled it. I havent faced it before and dint know abt it. Leaving this here for others to see. https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – leoOrion Sep 29 '20 at 04:50
  • Yes, the place where you append would change. I dont remember the tree traversals order. Ill leave that to you. – leoOrion Sep 29 '20 at 05:21
0

You can have preOrder yield the values and collect them in a list when you call it.

class Node:
    def __init__(self, data, left=None, right=None):
        self.left = left
        self.right = right
        self.data = data
    
    def preOrder(self): 
        yield self.data
        if self.left:
            yield from self.left.preOrder()
        if self.right:
            yield from self.right.preOrder()


root = Node(2,Node(1,Node(6),Node(3)),Node(3,None,Node(9)))
print(list(root.preOrder())) 

yield from needs at least python 3.3 but I don't think that's an issue these days.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61