Blogs Hub

by AskGif | Aug 09, 2018 | Category :coding

How to implement PreOrder Traversal in Binary Tree?

How to implement PreOrder Traversal in Binary Tree?

<p>In pre-order traversal, each node is processed before (pre) either of it's sub-trees. This is the simplest traversal to understand. However, even though each node is processed before the subtrees, it still requires that some information must be maintained while moving down the tree.</p> <p>Preorder traversal is defined as follows:</p> <p>- Visit the root.</p> <p>- Traverse the left subtree in Preorder.</p> <p>- Traverse the right subtree in Preorder.</p> <p>Java code for above implement 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); PrintPreOrderTraversal(root); } private static void PrintPreOrderTraversal(Node treeNode) { if(treeNode == null) return; System.out.println(treeNode.data); PrintPreOrderTraversal(treeNode.left); PrintPreOrderTraversal(treeNode.right); } } </code></pre> <pre class="language-markup"><code>output: 1 2 4 5 3</code></pre>

read more...