Java program to perform the postorder tree traversal
Here's a Java program to perform postorder traversal of a binary tree:
class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; } } public class PostorderTraversal { Node root; public PostorderTraversal() { root = null; } void postorder(Node node) { if (node == null) { return; } postorder(node.left); postorder(node.right); System.out.print(node.data + " "); } public static void main(String[] args) { PostorderTraversal tree = new PostorderTraversal(); 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(tree.root); } }Sourcwww:e.theitroad.com
Explanation:
The program first defines a Node
class to represent a node in the binary tree. Each Node
object has a data
field to store the integer value at the node, as well as left
and right
fields to represent the left and right subtrees.
The program then defines a PostorderTraversal
class to represent the binary tree. The root
field represents the root node of the tree.
The postorder
method performs a recursive postorder traversal of the binary tree. The method first checks if the current node is null
. If it is, the method simply returns. Otherwise, the method first recursively visits the left subtree, then the right subtree, and finally prints the value of the current node.
The main
method creates a new PostorderTraversal
object and initializes the root node and its left and right subtrees. It then calls the postorder
method on the root node to perform the postorder traversal of the binary tree. The result is printed to the console.