Blogs Hub

by AskGif | Aug 09, 2018 | Category :coding

How to implement PostOrder Traversal in Binary Tree?

How to implement PostOrder Traversal in Binary Tree?

<p>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.</p> <p>In PostOrder traversal, the root is visited after both subtrees. PostOrder traversal is defined as follows:</p> <p>- Traverse the left subtree in PostOrder.</p> <p>- Traverse the right subtree in PostOrder.</p> <p>- Visit the root.</p> <p>Java implementation of above traversal is as below:</p> <pre class="language-java"><code>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); } } </code></pre> <pre class="language-markup"><code>4 5 2 3 1 </code></pre>

read more...