Postorder traversal is a method of traversing a binary tree where nodes are visited in the following order:
This bottom-up approach is especially useful for operations where children need to be processed before their parent, such as when deleting a tree or evaluating expression trees.
Input Tree:
Expected Postorder Traversal Output:
[4, 5, 2, 3, 1]
Input Tree:
Expected Output:
[40,30,20,10]
Postorder traversal follows the Left → Right → Root sequence, ensuring that all descendants of a node are processed before the node itself. This order is particularly beneficial when you need to delete nodes or evaluate expressions that depend on the values of child nodes before combining them at the parent.
https://leetcode.com/problems/binary-tree-postorder -traversal
Loading component...
Loading component...
INPUT: Test Case 1: Simple Tree
OUTPUT: [4, 5, 2, 3, 1]
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
System.out.println("Postorder Traversal:");
postorder(root);
}//function end
public static void postorder(TreeNode root) {
if (root == null){
return;
}//If End
postorder(root.left);
postorder(root.right);
System.out.print(root.val + " ");
}//function end
static class TreeNode {
int val;
TreeNode left , right;
TreeNode(int val){
this.val = val;
this.left = this.right = null;
}
} // Class end