Trees / Beginner
Postorder Traversal Visualizer
Both subtrees first, the node last.
Start the Postorder Traversal simulation → Step forward and back, change the input, follow the code line by line in Java, Python, C++, C or JavaScript. Free, no sign-up.
Time and space complexity
| Best time | O(n) |
|---|---|
| Average time | O(n) |
| Worst time | O(n) |
| Extra space | O(h) |
Worked example, step by step
The same steps the simulator shows, on a small input.
- Postorder traversal: left subtree, right subtree and the node itself, in the order shown in the code.
- At node 50.
- Go left from 50.
- At node 30.
- Go left from 30.
- At node 20.
- Visit 20.
- Back at 30.
- Go right from 30.
- At node 40.
- Go left from 40.
- At node 35.
- Visit 35.
- Back at 40.
- Visit 40.
- Back at 30.
- Visit 30.
- Back at 50.
- Go right from 50.
- At node 70.
- … 12 more steps …
- Visit 70.
- Back at 50.
- Visit 50.
- Done. Visit order: 20, 35, 40, 30, 65, 60, 80, 70, 50.
Postorder traversal in Java, Python, C++, C and JavaScript
void postorder(Node n) {
if (n == null) return;
postorder(n.left);
postorder(n.right);
visit(n);
}
def postorder(n):
if n is None:
return
postorder(n.left)
postorder(n.right)
visit(n)
void postorder(Node* n) {
if (!n) return;
postorder(n->left);
postorder(n->right);
visit(n);
}
void postorder(struct Node* n) {
if (n == NULL) return;
postorder(n->left);
postorder(n->right);
visit(n);
}
function postorder(n) {
if (n === null) return;
postorder(n.left);
postorder(n.right);
visit(n);
}In an interview
Use postorder when a parent needs answers from its children: tree height, diameter, deleting a tree.