145. Binary tree postorder traversal

Given the root of a binary tree, return the postorder traversal of its nodes' values. c

  • code
class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        self.res = []

        def post(root):
            if root:
                post(root.left)
                post(root.right)
                self.res.append(root.val)

        post(root)
        return self.res

  • code modified pre-order
class Solution:
    def postorderTraversal(self, root):
        traversal, stack = [], [root]
        while stack:
            node = stack.pop()
            if node:
                # pre-order, right first
                traversal.append(node.val)
                stack.append(node.left)
                stack.append(node.right)

        # reverse result
        return traversal[::-1]