How to implement PostOrder Traversal in Binary Tree?
💻 coding

How to implement PostOrder Traversal in Binary Tree?

1 min read 171 words
1 min read
ShareWhatsAppPost on X
  • 1PostOrder Traversal visits the left subtree, then the right subtree, and finally the root node.
  • 2In PostOrder traversal, the root is processed after both its left and right children.
  • 3The provided Java implementation demonstrates how to perform PostOrder Traversal in a binary tree.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"PostOrder Traversal visits the left subtree, then the right subtree, and finally the root node."

How to implement PostOrder Traversal in Binary Tree?

PostOrder Traversal is different from InOrder Traversal and PreOrder Traversal. In this Traversal approach we first traverse through left and then right and at the end, we traverse to the node data.

In PostOrder traversal, the root is visited after both subtrees. PostOrder traversal is defined as follows:

- Traverse the left subtree in PostOrder.

- Traverse the right subtree in PostOrder.

- Visit the root.

Java implementation of above traversal is as below:

package askgif.tree;

class Node
{
 int data;
 Node left, right;
 
 public Node(int item)
 {
 data = item;
 left = right = null;
 }
}

class BinaryTree
{
 Node root;
 
 BinaryTree()
 {
 root = null;
 }
 
}

public class TreeQuestions {

	public static void main(String[] args) {
		BinaryTree binaryTree = new BinaryTree();
		Node root = new Node(1);
		binaryTree.root = root;
		binaryTree.root.left = new Node(2);
		binaryTree.root.right = new Node(3);
		binaryTree.root.left.left = new Node(4);
		binaryTree.root.left.right = new Node(5);
 
 PrintPostOrderTraversal(root);

	}

	private static void PrintPostOrderTraversal(Node treeNode) {
		if(treeNode == null)
			return;
		PrintPostOrderTraversal(treeNode.left);
		PrintPostOrderTraversal(treeNode.right);
		System.out.println(treeNode.data);
		
	}

}
4
5
2
3
1

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 9 August 2018 · 1 min read · 171 words

Part of AskGif Blog · coding

You might also like