Algo-Sim › Binary Trees & BST

Postorder Traversal (Recursive)

Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Recursive depth-first traversal that outputs each node after both subtrees.

Problem

Given the root of a binary tree, return its values in postorder: the left subtree, then the right subtree, then the node itself. This version recurses.

Constraints

Edge cases to test

Follow-up questions

Can you do it without recursion?
One stack plus the last node output, or a node–right–left preorder reversed at the end (two stacks): O(n).
When is postorder the natural order?
Whenever a node needs its children’s answers first: heights, subtree sums, deleting or freeing a tree.

Solution

Java

public List<Integer> postorderTraversal(TreeNode root) {
    List<Integer> out = new ArrayList<>();
    visit(root, out);
    return out;
}

private void visit(TreeNode node, List<Integer> out) {
    if (node == null) return;
    visit(node.left, out);
    visit(node.right, out);
    out.add(node.val);
}

Python

def postorder_traversal(root):
    out = []

    def visit(node):
        if not node:
            return
        visit(node.left)
        visit(node.right)
        out.append(node.val)

    visit(root)
    return out

C++

#include <bits/stdc++.h>
using namespace std;
class Solution {
  public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> out;
        visit(root, out);
        return out;
    }
    void visit(TreeNode *node, vector<int> &out) {
        if (!node)
            return;
        visit(node->left, out);
        visit(node->right, out);
        out.push_back(node->val);
    }
};

More Binary Trees & BST problems