Postorder tree traversal is a technique used to traverse a tree data structure.
It is a depth-first traversal technique in which the nodes are visited in the order of their children before visiting the node itself.
In this traversal method, the left subtree is visited first, followed by the right subtree, and then the root node.
To perform postorder tree traversal, we can use recursion.
The basic idea is to traverse the left subtree recursively, then traverse the right subtree recursively, and finally, visit the root node.
Here is the Java program to perform postorder tree traversal using recursion:
class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; } } class BinaryTree { Node root; BinaryTree() { root = null; } void postorder(Node node) { if (node == null) return; postorder(node.left); postorder(node.right); System.out.print(node.data + " "); } void postorder() { postorder(root); } public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println("Postorder traversal of binary tree is: "); tree.postorder(); } }
In this program, we have defined a Node
class to represent a node in the tree.
The BinaryTree
class has a root
node and a postorder
method that performs postorder traversal.
The postorder
method takes a Node
object as an argument and recursively traverses the left and right subtrees before visiting the node itself.
The postorder
method also prints the data of each node in postorder traversal.
The postorder
method is called from the postorder
method of the BinaryTree
class to traverse the entire tree.
In the main
method, we create a binary tree with five nodes and perform postorder traversal using the postorder
method.
This is how we can perform postorder tree traversal using recursion in Java.