Blogs Hub

by AskGif | Aug 09, 2018 | Category :coding

How to implement InOrder Traversal in Binary Tree?

How to implement InOrder Traversal in Binary Tree?

<p>The Technique for traversal in an Inorder is slightly different from what we were doing in PreOrder Traversal. Here we go through left node, then data and then the right node.</p> <p>In an InOrder traversal, the root is visited between the subtrees. InOrder traversal is defined as follows:</p> <p>- Traverse the left subtree in InOrder.</p> <p>- Visit the root.</p> <p>- Traverse the right subtree in InOrder.</p> <p>Java Code for above Implementation 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); PrintInOrderTraversal(root); } private static void PrintInOrderTraversal(Node treeNode) { if(treeNode == null) return; PrintInOrderTraversal(treeNode.left); System.out.println(treeNode.data); PrintInOrderTraversal(treeNode.right); } } </code></pre> <pre class="language-markup"><code>4 2 5 1 3 </code></pre>

read more...