{"id":27638,"date":"2018-04-09T20:17:42","date_gmt":"2018-04-09T14:47:42","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27638"},"modified":"2018-09-14T19:08:19","modified_gmt":"2018-09-14T13:38:19","slug":"python-algorithm-iterative-postorder-traversal-set-2-using-one-stack","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-algorithm-iterative-postorder-traversal-set-2-using-one-stack\/","title":{"rendered":"Python  Algorithm &#8211; Iterative Postorder Traversal | Set 2 (Using One Stack)"},"content":{"rendered":"<p>We have discussed a simple iterative postorder traversal using two stacks in the previous post. In this post, an approach with only one stack is discussed.<span id=\"more-114897\"><\/span><\/p>\n<p>The idea is to move down to leftmost node using left pointer. While moving down, push root and root\u2019s right child to stack. Once we reach leftmost node, print it if it doesn\u2019t have a right child. If it has a right child, then change root so that the right child is processed before.<\/p>\n<p>Following is detailed algorithm.<\/p>\n<pre>1.1 Create an empty stack\r\n2.1 Do following while root is not NULL\r\n    a) Push root's right child and then root to stack.\r\n    b) Set root as root's left child.\r\n2.2 Pop an item from stack and set it as root.\r\n    a) If the popped item has a right child and the right child \r\n       is at top of stack, then remove the right child from stack,\r\n       push the root back and set root as root's right child.\r\n    b) Else print root's data and set root as NULL.\r\n2.3 Repeat steps 2.1 and 2.2 while stack is not empty.<\/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 one stack.<\/p>\n<pre>1. Right child of 1 exists. \r\n   Push 3 to stack. Push 1 to stack. Move to left child.\r\n        Stack: 3, 1\r\n\r\n2. Right child of 2 exists. \r\n   Push 5 to stack. Push 2 to stack. Move to left child.\r\n        Stack: 3, 1, 5, 2\r\n\r\n3. Right child of 4 doesn't exist. '\r\n   Push 4 to stack. Move to left child.\r\n        Stack: 3, 1, 5, 2, 4\r\n\r\n4. Current node is NULL. \r\n   Pop 4 from stack. Right child of 4 doesn't exist. \r\n   Print 4. Set current node to NULL.\r\n        Stack: 3, 1, 5, 2\r\n\r\n5. Current node is NULL. \r\n    Pop 2 from stack. Since right child of 2 equals stack top element, \r\n    pop 5 from stack. Now push 2 to stack.     \r\n    Move current node to right child of 2 i.e. 5\r\n        Stack: 3, 1, 2\r\n\r\n6. Right child of 5 doesn't exist. Push 5 to stack. Move to left child.\r\n        Stack: 3, 1, 2, 5\r\n\r\n7. Current node is NULL. Pop 5 from stack. Right child of 5 doesn't exist. \r\n   Print 5. Set current node to NULL.\r\n        Stack: 3, 1, 2\r\n\r\n8. Current node is NULL. Pop 2 from stack. \r\n   Right child of 2 is not equal to stack top element. \r\n   Print 2. Set current node to NULL.\r\n        Stack: 3, 1\r\n\r\n9. Current node is NULL. Pop 1 from stack. \r\n   Since right child of 1 equals stack top element, pop 3 from stack. \r\n   Now push 1 to stack. Move current node to right child of 1 i.e. 3\r\n        Stack: 1\r\n\r\n10. Repeat the same as above steps and Print 6, 7 and 3. \r\n    Pop 1 and Print 1.<\/pre>\n<p><strong>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program for iterative postorder traversal<br\/># using one stack<br\/> <br\/># Stores the answer<br\/>ans = []<br\/> <br\/># A Binary tree node<br\/>class Node:<br\/>     <br\/>    # Constructor to create a new node<br\/>    def __init__(self, data):<br\/>        self.data = data<br\/>        self.left = None<br\/>        self.right = None<br\/> <br\/>def peek(stack):<br\/>    if len(stack) &gt; 0:<br\/>        return stack[-1]<br\/>    return None<br\/># A iterative function to do postorder traversal of <br\/># a given binary tree<br\/>def postOrderIterative(root):<br\/>         <br\/>    # Check for empty tree<br\/>    if root is None:<br\/>        return<br\/> <br\/>    stack = []<br\/>     <br\/>    while(True):<br\/>         <br\/>        while (root):<br\/>             # Push root&#039;s right child and then root to stack<br\/>             if root.right is not None:<br\/>                stack.append(root.right)<br\/>             stack.append(root)<br\/> <br\/>             # Set root as root&#039;s left child<br\/>             root = root.left<br\/>         <br\/>        # Pop an item from stack and set it as root<br\/>        root = stack.pop()<br\/> <br\/>        # If the popped item has a right child and the<br\/>        # right child is not processed yet, then make sure<br\/>        # right child is processed before root<br\/>        if (root.right is not None and<br\/>            peek(stack) == root.right):<br\/>            stack.pop() # Remove right child from stack <br\/>            stack.append(root) # Push root back to stack<br\/>            root = root.right # change root so that the <br\/>                             # righ childis processed next<br\/> <br\/>        # Else print root&#039;s data and set root as None<br\/>        else:<br\/>            ans.append(root.data) <br\/>            root = None<br\/> <br\/>        if (len(stack) &lt;= 0):<br\/>                break<br\/> <br\/># Driver pogram to test above function<br\/>root = Node(1)<br\/>root.left = Node(2)<br\/>root.right = Node(3)<br\/>root.left.left = Node(4)<br\/>root.left.right = Node(5)<br\/>root.right.left = Node(6)<br\/>root.right.right = Node(7)<br\/> <br\/>print &quot;Post Order traversal of binary tree is&quot;<br\/>postOrderIterative(root)<br\/>print ans<br\/> <br\/># This code is contributed by Nikhil Kumar Singh(nickzuck_007)<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Post Order traversal of binary tree is\r\n[4, 5, 2, 6, 7, 3, 1]<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Python  Algorithm &#8211; Iterative Postorder Traversal | Set 2 (Using One Stack) &#8211; Stack &#8211; We have discussed a simple iterative postorder traversal <\/p>\n","protected":false},"author":1,"featured_media":31275,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73012,79607],"tags":[81802,81938,81942,81937,81953,81940,81804,81941],"class_list":["post-27638","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures","category-stack","tag-inorder-preorder-postorder-traversal-without-recursion-in-c","tag-iterative-inorder-traversal","tag-iterative-inorder-traversal-without-stack","tag-iterative-preorder-traversal","tag-non-recursive-postorder-traversal-algorithm","tag-postorder-traversal-algorithm-using-stack","tag-postorder-traversal-without-recursion-and-stack","tag-preorder-traversal-without-recursion-without-stack"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27638","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=27638"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27638\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31275"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27638"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27638"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27638"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}