Simple iterative and recursive solutions


  • 5
    C

    Solution 1, Iterative

    def preorderTraversal(self, root):
        stack, ans =[root], []
        while stack:
            node = stack.pop(-1)
            while node:
                if node.right:
                    stack.append(node.right)
                ans.append(node.val)
                node=node.left
        return ans
    



    Solution 2 , Recursive

    def preorderTraversal(self, root):
        def DFS(node):
            if node:
                ans.append(node.val)
                DFS(node.left)
                DFS(node.right)
        ans = []
        DFS(root)
        return ans

Log in to reply
 

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