Iterative solution using a stack in Python


  • 0
    class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        values = []
        stack = []
        stack.append (root)
        
        while stack:
            top_node = stack.pop()
            if top_node:
                values.append(top_node.val)
                stack.append(top_node.right)
                stack.append(top_node.left)
        
        return values

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.