{"id":27689,"date":"2018-04-09T20:22:43","date_gmt":"2018-04-09T14:52:43","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27689"},"modified":"2018-09-11T19:38:46","modified_gmt":"2018-09-11T14:08:46","slug":"c-algorithm-iterative-postorder-traversal-set-1-using-two-stacks","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-algorithm-iterative-postorder-traversal-set-1-using-two-stacks\/","title":{"rendered":"C Algorithm &#8211; Iterative Postorder Traversal | Set 1 (Using Two Stacks)"},"content":{"rendered":"<p>We have discussed iterative inorder and iterative preorder traversals. In this post, iterative postorder traversal is discussed which is more complex than the other two traversals (due to its nature of non-tail recursion, there is an extra statement after the final recursive call to itself). <span id=\"more-26410\"><\/span>The postorder traversal can easily be done using two stacks though. The idea is to push reverse postorder traversal to a stack. Once we have reverse postorder traversal in a stack, we can just pop all items one by one from the stack and print them, this order of printing will be in postorder because of LIFO property of stacks. Now the question is, how to get reverse post order elements in a stack \u2013 the other stack is used for this purpose. For example, in the following tree, we need to get 1, 3, 7, 6, 2, 5, 4 in a stack. If take a closer look at this sequence, we can observe that this sequence is very similar to preorder traversal. The only difference is right child is visited before left child and therefore sequence is \u201croot right left\u201d instead of \u201croot left right\u201d. So we can do something like iterative preorder traversal with following differences.<br \/>\na) Instead of printing an item, we push it to a stack.<br \/>\nb) We push left subtree before right subtree.<\/p>\n<p>Following is the complete algorithm. After step 2, we get reverse postorder traversal in second stack. We use first stack to get this order.<\/p>\n<pre>1. Push root to first stack.\r\n2. Loop while first stack is not empty\r\n   2.1 Pop a node from first stack and push it to second stack\r\n   2.2 Push left and right children of the popped node to first stack\r\n3. Print contents of second stack<\/pre>\n<p>Let us consider the following tree<\/p>\n<p>Following are the steps to print postorder traversal of the above tree using two stacks.<\/p>\n<pre>1. Push 1 to first stack.\r\n      First stack: 1\r\n      Second stack: Empty\r\n\r\n2. Pop 1 from first stack and push it to second stack. \r\n   Push left and right children of 1 to first stack\r\n      First stack: 2, 3\r\n      Second stack: 1\r\n\r\n3. Pop 3 from first stack and push it to second stack. \r\n   Push left and right children of 3 to first stack\r\n      First stack: 2, 6, 7\r\n      Second stack:1, 3\r\n\r\n4. Pop 7 from first stack and push it to second stack.\r\n      First stack: 2, 6\r\n      Second stack:1, 3, 7\r\n\r\n5. Pop 6 from first stack and push it to second stack.\r\n      First stack: 2\r\n      Second stack:1, 3, 7, 6\r\n\r\n6. Pop 2 from first stack and push it to second stack. \r\n   Push left and right children of 2 to first stack\r\n      First stack: 4, 5\r\n      Second stack:1, 3, 7, 6, 2\r\n\r\n7. Pop 5 from first stack and push it to second stack.\r\n      First stack: 4\r\n      Second stack: 1, 3, 7, 6, 2, 5\r\n\r\n8. Pop 4 from first stack and push it to second stack.\r\n      First stack: Empty\r\n      Second stack: 1, 3, 7, 6, 2, 5, 4\r\n\r\nThe algorithm stops since there is no more item in first stack. \r\nObserve that content of second stack is in postorder fashion. Print them.<\/pre>\n<p>Following is C implementation of iterative postorder traversal using two stacks.<\/p>\n<p><strong>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">#include &lt;stdio.h&gt;<br\/>#include &lt;stdlib.h&gt;<br\/> <br\/>\/\/ Maximum stack size<br\/>#define MAX_SIZE 100<br\/> <br\/>\/\/ A tree node<br\/>struct Node<br\/>{<br\/>    int data;<br\/>    struct Node *left, *right;<br\/>};<br\/> <br\/>\/\/ Stack type<br\/>struct Stack<br\/>{<br\/>    int size;<br\/>    int top;<br\/>    struct Node* *array;<br\/>};<br\/> <br\/>\/\/ A utility function to create a new tree node<br\/>struct Node* newNode(int data)<br\/>{<br\/>    struct Node* node = (struct Node*) malloc(sizeof(struct Node));<br\/>    node-&gt;data = data;<br\/>    node-&gt;left = node-&gt;right = NULL;<br\/>    return node;<br\/>}<br\/> <br\/>\/\/ A utility function to create a stack of given size<br\/>struct Stack* createStack(int size)<br\/>{<br\/>    struct Stack* stack =<br\/>            (struct Stack*) malloc(sizeof(struct Stack));<br\/>    stack-&gt;size = size;<br\/>    stack-&gt;top = -1;<br\/>    stack-&gt;array =<br\/>           (struct Node**) malloc(stack-&gt;size * sizeof(struct Node*));<br\/>    return stack;<br\/>}<br\/> <br\/>\/\/ BASIC OPERATIONS OF STACK<br\/>int isFull(struct Stack* stack)<br\/>{  return stack-&gt;top - 1 == stack-&gt;size; }<br\/> <br\/>int isEmpty(struct Stack* stack)<br\/>{  return stack-&gt;top == -1;  }<br\/> <br\/>void push(struct Stack* stack, struct Node* node)<br\/>{<br\/>    if (isFull(stack))<br\/>        return;<br\/>    stack-&gt;array[++stack-&gt;top] = node;<br\/>}<br\/> <br\/>struct Node* pop(struct Stack* stack)<br\/>{<br\/>    if (isEmpty(stack))<br\/>        return NULL;<br\/>    return stack-&gt;array[stack-&gt;top--];<br\/>}<br\/> <br\/>\/\/ An iterative function to do post order traversal of a given binary tree<br\/>void postOrderIterative(struct Node* root)<br\/>{<br\/>    if (root == NULL) <br\/>        return;<br\/> <br\/>    \/\/ Create two stacks<br\/>    struct Stack* s1 = createStack(MAX_SIZE);<br\/>    struct Stack* s2 = createStack(MAX_SIZE);<br\/> <br\/>    \/\/ push root to first stack<br\/>    push(s1, root);<br\/>    struct Node* node;<br\/> <br\/>    \/\/ Run while first stack is not empty<br\/>    while (!isEmpty(s1))<br\/>    {<br\/>        \/\/ Pop an item from s1 and push it to s2<br\/>        node = pop(s1);<br\/>        push(s2, node);<br\/> <br\/>        \/\/ Push left and right children of removed item to s1<br\/>        if (node-&gt;left)<br\/>            push(s1, node-&gt;left);<br\/>        if (node-&gt;right)<br\/>            push(s1, node-&gt;right);<br\/>    }<br\/> <br\/>    \/\/ Print all elements of second stack<br\/>    while (!isEmpty(s2))<br\/>    {<br\/>        node = pop(s2);<br\/>        printf(&quot;%d &quot;, node-&gt;data);<br\/>    }<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    \/\/ Let us construct the tree shown in above figure<br\/>    struct Node* root = NULL;<br\/>    root = newNode(1);<br\/>    root-&gt;left = newNode(2);<br\/>    root-&gt;right = newNode(3);<br\/>    root-&gt;left-&gt;left = newNode(4);<br\/>    root-&gt;left-&gt;right = newNode(5);<br\/>    root-&gt;right-&gt;left = newNode(6);<br\/>    root-&gt;right-&gt;right = newNode(7);<br\/> <br\/>    postOrderIterative(root);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>4 5 2 6 7 3 1<\/pre>\n<p>Following is overview of the above post.<br \/>\nIterative preorder traversal can be easily implemented using two stacks. The first stack is used to get the reverse postorder traversal in second stack. The steps to get reverse postorder are similar to <a href=\"http:\/\/www.geeksforgeeks.org\/iterative-preorder-traversal\/\" target=\"_blank\" rel=\"noopener noreferrer\">iterative preorder<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>C Algorithm &#8211; Iterative Postorder Traversal | Set 1 (Using Two Stacks)  &#8211; Stack &#8211; We have discussed iterative inorder and iterative preorder traversals<\/p>\n","protected":false},"author":1,"featured_media":31265,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73012,79607],"tags":[81965,81802,81938,81937,81953,81964,81940,81804],"class_list":["post-27689","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures","category-stack","tag-binary-tree-postorder-traversal-leetcode","tag-inorder-preorder-postorder-traversal-without-recursion-in-c","tag-iterative-inorder-traversal","tag-iterative-preorder-traversal","tag-non-recursive-postorder-traversal-algorithm","tag-postorder-traversal-algorithm-of-a-binary-tree","tag-postorder-traversal-algorithm-using-stack","tag-postorder-traversal-without-recursion-and-stack"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27689","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=27689"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27689\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31265"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27689"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27689"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27689"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}