Python recursive and iterative solutions.


  • 0
    C
    # recursively 
    def postorderTraversal1(self, root):
        res = []
        self.dfs(root, res)
        return res
        
    def dfs(self, root, res):
        if root:
            self.dfs(root.left, res)
            self.dfs(root.right, res)
            res.append(root.val)
    
    # iteratively        
    def postorderTraversal(self, root):
        res, stack = [], [root]
        while stack:
            node = stack.pop()
            if node:
                res.append(node.val)
                stack.append(node.left)
                stack.append(node.right)
        return res[::-1]

  • 0
    C

    Another recursive solution, based on the iterative solution above, quite interesting.

    def postorderTraversal(self, root):
        res = []
        self.dfs(root, res)
        return res[::-1]
    
    def dfs(self, root, res):
        if root:
            res.append(root.val)
            self.dfs(root.right, res)
            self.dfs(root.left, res)

Log in to reply
 

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