Python solutions (recursively and iteratively).


  • 9
    C
    # recursively
    def preorderTraversal1(self, root):
        res = []
        self.dfs(root, res)
        return res
        
    def dfs(self, root, res):
        if root:
            res.append(root.val)
            self.dfs(root.left, res)
            self.dfs(root.right, res)
    
    # iteratively
    def preorderTraversal(self, root):
        stack, res = [root], []
        while stack:
            node = stack.pop()
            if node:
                res.append(node.val)
                stack.append(node.right)
                stack.append(node.left)
        return res

  • 1

    For DFS, two lines will be too much!

    return [] if not root else [root.val]+self.preorderTraversal(root.left)+self.preorderTraversal(root.right)


Log in to reply
 

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