Postorder traversal

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

Time O(n)Space O(h)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

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

Code

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);
}
static void postorder(TreeNode node, List<Integer> result) {
    if (node == null) return;
    postorder(node.left, result);
    postorder(node.right, result);
    result.add(node.val);
}
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)

Tips

In the .NET library

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