Tree: Preorder Traversal

  • + 0 comments

    Python3

    def preOrder(root):
        # it would be useful to have a stack here to keep track of the next node to visit
        # if I start going down a left child, the next node to visit would be the right child
        # I also will need to set my current pointer to the current node
        # and create a result array
        
        cur = root
        stack = []
           
        # my loop is finished when
        # cur is None - OR
        # stack is None - stack is only None at beginning or end
        
        while cur or stack:
            if cur:
                print(cur.info, end=' ')
                stack.append(cur.right)
                cur = cur.left
            else:
                cur = stack.pop()