Easy understand python solution !!!


  • 0
    Y

    Return the most left node in stack at one time,and push it`s left and right node into stack.

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

Log in to reply
 

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