Python iterative solution


  • 0
    G
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        # @param {TreeNode} root
        # @return {integer[]}
        def preorderTraversal(self, root):
            if not root:
                return []
    
            result, queue = [], [root]
            while queue:
                curNode = queue.pop()
                if curNode:
                    result.append(curNode.val)
                    queue.append(curNode.right)
                    queue.append(curNode.left)
    
            return result

  • 0
    C

    Nice answer, while it can be also rewritten as:

    def preorderTraversal(self, root):
        if not root:
            return []
        stack, res = [root], []
        while stack:
            curr = stack.pop()
            res.append(curr.val)
            if curr.right:
                stack.append(curr.right)
            if curr.left:
                stack.append(curr.left)
        return res
    

Log in to reply
 

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