Post-Order Traversal

Tree Traversal Algorithm: How do you traverse a binary tree post-order (recursively and iteratively)? What are its use cases?

Assume:

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.right = None
        self.left = None

Iterative

# iterative 

def postorder_iterative(node):
    res_temp = []
    res = []
    if not node:
        return res
    stack = []
    stack.append(node)
    while stack:
        node = stack.pop()
        res_temp.append(node.val) # additional logic here!
		if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    while res_temp:
        res.append(res_temp.pop()) # or here! reversed(res_temp) is the postorder
		return res

Recursive

# recursive

def postorder_recursive(node, res=None):
    if node is None:
        return []
    if res is None:
        res = []
    postorder_recursive(node.left, res)
    postorder_recursive(node.right, res)
    res.append(node.val) # additional logic here!
		return res