Postorder traversal

Both subtrees first, then the node. Children are always finished before their parent.

Time O(n)Space O(h)Code C++, Python and C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

A node is recorded only after everything below it is done. The root is always last.

Code

void postorder(TreeNode* node, vector<int>& result) {
    if (!node) return;
    postorder(node->left, result);
    postorder(node->right, result);
    result.push_back(node->val);
}
def postorder(node: TreeNode | None, result: list[int]) -> None:
    if node is None: return
    postorder(node.left, result)
    postorder(node.right, result)
    result.append(node.val)
public static void Postorder(TreeNode node, List<int> result) {
    if (node == null) return;
    Postorder(node.left, result);
    Postorder(node.right, result);
    result.Add(node.val);
}

Tips

In the .NET library

Disposing a tree of owned resources is postorder: dispose the children, then the parent.