Topic 69 of 78
Postorder Traversal
Overview
Postorder Traversal is a Tree DFS where the order is: Left Child, Right Child, Current Node. The parent is processed absolutely last. This is exactly what you need when you are deleting a tree, because you cannot delete a parent node until all of its children have safely been deleted first.
Syntax
Leaves are processed first. The root of the entire tree is printed absolutely last.
Left, Right, Root
java
public void postorder(TreeNode root) {
if (root == null) return;
postorder(root.left); // 1. Left
postorder(root.right); // 2. Right
System.out.print(root.val); // 3. Root (Process)
}Common Pitfalls
- It is the hardest of the three traversals to implement iteratively. Stick to recursion if possible!
Interview Tips
- Postorder means the 'Root' is processed POST (after) its children.
Real-World Example
Evaluating Mathematical Syntax Trees (like 3 * (4 + 5)). You must evaluate the child operations (4 + 5) before applying the parent operation (* 3).
example
java
// Postorder evaluation of syntax trees ensures proper order of operations.