{"id":27628,"date":"2018-04-04T19:36:53","date_gmt":"2018-04-04T14:06:53","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27628"},"modified":"2018-09-16T14:23:49","modified_gmt":"2018-09-16T08:53:49","slug":"java-program-inorder-tree-traversal-without-recursion","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-program-inorder-tree-traversal-without-recursion\/","title":{"rendered":"Java Program &#8211; Inorder Tree Traversal without Recursion"},"content":{"rendered":"<p>Using <a href=\"http:\/\/en.wikipedia.org\/wiki\/Stack_%28data_structure%29\" target=\"_blank\" rel=\"noopener\">Stack <\/a>is the obvious way to traverse tree without recursion. Below is an algorithm for traversing binary tree using stack. See <a href=\"http:\/\/neural.cs.nthu.edu.tw\/jang\/courses\/cs2351\/slide\/animation\/Iterative%20Inorder%20Traversal.pps\" target=\"_blank\" rel=\"noopener\">this <\/a>for step wise step execution of the algorithm.<\/p>\n<pre>1) Create an empty stack S.\r\n2) Initialize current node as root\r\n3) Push the current node to S and set current = current-&gt;left until current is NULL\r\n4) If current is NULL and stack is not empty then \r\n     a) Pop the top item from stack.\r\n     b) Print the popped item, set current = popped_item-&gt;right \r\n     c) Go to step 3.\r\n5) If current is NULL and stack is empty then we are done.\r\n<\/pre>\n<p>Let us consider the below tree for example<\/p>\n<pre>            1\r\n          \/   \\\r\n        2      3\r\n      \/  \\\r\n    4     5\r\n\r\nStep 1 Creates an empty stack: S = NULL\r\n\r\nStep 2 sets current as address of root: current -&gt; 1\r\n\r\nStep 3 Pushes the current node and set current = current-&gt;left until current is NULL\r\n     current -&gt; 1\r\n     push 1: Stack S -&gt; 1\r\n     current -&gt; 2\r\n     push 2: Stack S -&gt; 2, 1\r\n     current -&gt; 4\r\n     push 4: Stack S -&gt; 4, 2, 1\r\n     current = NULL\r\n\r\nStep 4 pops from S\r\n     a) Pop 4: Stack S -&gt; 2, 1\r\n     b) print \"4\"\r\n     c) current = NULL \/*right of 4 *\/ and go to step 3\r\nSince current is NULL step 3 doesn't do anything. \r\n\r\nStep 4 pops again.\r\n     a) Pop 2: Stack S -&gt; 1\r\n     b) print \"2\"\r\n     c) current -&gt; 5\/*right of 2 *\/ and go to step 3\r\n\r\nStep 3 pushes 5 to stack and makes current NULL\r\n     Stack S -&gt; 5, 1\r\n     current = NULL\r\n\r\nStep 4 pops from S\r\n     a) Pop 5: Stack S -&gt; 1\r\n     b) print \"5\"\r\n     c) current = NULL \/*right of 5 *\/ and go to step 3\r\nSince current is NULL step 3 doesn't do anything\r\n\r\nStep 4 pops again.\r\n     a) Pop 1: Stack S -&gt; NULL\r\n     b) print \"1\"\r\n     c) current -&gt; 3 \/*right of 5 *\/  \r\n\r\nStep 3 pushes 3 to stack and makes current NULL\r\n     Stack S -&gt; 3\r\n     current = NULL\r\n\r\nStep 4 pops from S\r\n     a) Pop 3: Stack S -&gt; NULL\r\n     b) print \"3\"\r\n     c) current = NULL \/*right of 3 *\/<\/pre>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ non-recursive java program for inorder traversal<br\/> <br\/>\/* importing the necessary class *\/<br\/>import java.util.Stack;<br\/> <br\/>\/* Class containing left and right child of current <br\/> node and key value*\/<br\/>class Node {<br\/> <br\/>    int data;<br\/>    Node left, right;<br\/> <br\/>    public Node(int item) {<br\/>        data = item;<br\/>        left = right = null;<br\/>    }<br\/>}<br\/> <br\/>\/* Class to print the inorder traversal *\/<br\/>class BinaryTree {<br\/> <br\/>    Node root;<br\/> <br\/>    void inorder() {<br\/>        if (root == null) {<br\/>            return;<br\/>        }<br\/>        <br\/>        \/\/keep the nodes in the path that are waiting to be visited<br\/>        Stack&lt;Node&gt; stack = new Stack&lt;Node&gt;();<br\/>        Node node = root;<br\/>         <br\/>        \/\/first node to be visited will be the left one<br\/>        while (node != null) {<br\/>            stack.push(node);<br\/>            node = node.left;<br\/>        }<br\/>         <br\/>        \/\/ traverse the tree<br\/>        while (stack.size() &gt; 0) {<br\/>           <br\/>            \/\/ visit the top node<br\/>            node = stack.pop();<br\/>            System.out.print(node.data + &quot; &quot;);<br\/>            if (node.right != null) {<br\/>                node = node.right;<br\/>                 <br\/>                \/\/ the next node to be visited is the leftmost<br\/>                while (node != null) {<br\/>                    stack.push(node);<br\/>                    node = node.left;<br\/>                }<br\/>            }<br\/>        }<br\/>    }<br\/> <br\/>    public static void main(String args[]) {<br\/>         <br\/>        \/* creating a binary tree and entering <br\/>         the nodes *\/<br\/>        BinaryTree tree = new BinaryTree();<br\/>        tree.root = new Node(1);<br\/>        tree.root.left = new Node(2);<br\/>        tree.root.right = new Node(3);<br\/>        tree.root.left.left = new Node(4);<br\/>        tree.root.left.right = new Node(5);<br\/>        tree.inorder();<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Time Complexity: O(n)<\/p>\n<p>Output:<\/p>\n<pre> 4 2 5 1 3<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>inorder tree travesal without recursion &#8211; Using Stack is the obvious way to traverse tree without recursion.Below is an algorithm for traversing binary tree<\/p>\n","protected":false},"author":1,"featured_media":31291,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[81802,81803,81805,81800,80775,81801,81804,81909],"class_list":["post-27628","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-coding","tag-inorder-preorder-postorder-traversal-without-recursion-in-c","tag-inorder-traversal-with-recursion","tag-inorder-traversal-with-recursion-in-c","tag-inorder-traversal-without-recursion-and-stack","tag-postorder-traversal-java","tag-postorder-traversal-without-recursion","tag-postorder-traversal-without-recursion-and-stack","tag-preorder-traversal-without-recursion"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27628","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27628"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27628\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31291"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27628"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27628"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27628"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}