SDE & MLE Prep

145. Binary Tree Postorder Traversal

Problem

Return the post-order traversal (left subtree, right subtree, node) of a binary tree.

Example: [1,null,2,3] → [3,2,1]

Constraints: follow-up: iteratively.

Postorder (left, right, root) is the reverse of a modified preorder (root, right, left): run preorder pushing left before right, then reverse the output.

Complexity: O(n) time, O(n) space.

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        out, st = [], [root] if root else []
        while st:
            node = st.pop()
            out.append(node.val)
            if node.left:
                st.append(node.left)
            if node.right:
                st.append(node.right)
        return out[::-1]