The challenge
Return the values in left → right → root order with one stack.
Compare node identities, not values: different nodes may have equal values.
Example
Balanced example: [2, 6, 4, 10, 14, 12, 8].
Use the walkthrough below to inspect the input and each state change.
See Postorder, step by step
Follow the branches. Watch the state change.
View child pointers & node state
| Node | Value | Left | Right | State |
|---|---|---|---|---|
| A | 8 | B | C | — |
| B | 4 | D | E | — |
| C | 12 | F | G | — |
| D | 2 | null | null | — |
| E | 6 | null | null | — |
| F | 10 | null | null | — |
| G | 14 | null | null | — |
Inspect the input.
Labels identify node objects; numbers are their values. Left and right child pointers define the tree.
root = A:8View original input
A:8 [L:B, R:C] · B:4 [L:D, R:E] · C:12 [L:F, R:G] · D:2 [L:null, R:null] · E:6 [L:null, R:null] · F:10 [L:null, R:null] · G:14 [L:null, R:null]
Node IDs stay distinct even when values repeat. Pointer mutations update the diagram; removed nodes remain in the state table for reference.
Put it into code
Remember the last completed subtree to know whether the right side still needs processing.
Nodes store value, left, and right. C++ uses C++17 or later.
from collections import deque
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def postorder(root):
out, stack, node, last = [], [], root, None
while node or stack:
if node:
stack.append(node)
node = node.left
else:
top = stack[-1]
if top.right and last is not top.right:
node = top.right
else:
out.append(top.value)
last = stack.pop()
return out
#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
#include <map>
#include <optional>
#include <queue>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
struct Node {
long long value;
Node *left = nullptr, *right = nullptr;
explicit Node(long long v) : value(v) {}
};
vector<long long> postorder(Node* root) {
vector<long long> out;
stack<Node*> pending;
Node *node = root, *last = nullptr;
while (node || !pending.empty()) {
if (node) { pending.push(node); node = node->left; }
else {
Node* top = pending.top();
if (top->right && last != top->right) node = top->right;
else {
out.push_back(top->value);
last = top; pending.pop();
}
}
}
return out;
}