• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[Solved] PostOrder Traversal of Binary Tree Without Recursion

Aniruddha Chaudhari/8805/0
Misc

Traversing elements in postorder traversal with recursion is easy. You can read the postorder traversal in detail where I have explained it with binary tree example and code.

Table of Contents

  • Problem Statement
  • Binary Tree Example
  • Algorithm
  • Python Program for PostOrder Traversal without Recursion:

Problem Statement

You have given a binary tree. Implement PostOrder Traversal Without Recursion.

Here we are going to use the iterative method to traverse binary tree elements

(This problem was asked in the OVH cloud interview round. You have to write working code on the whiteboard.)

Binary Tree Example

reorder, inorder and post order traversal

The postorder traversal of the Binary tree is 7 3 1 6 5 4.

Algorithm

Here we are going to use the stack. Each element in the stack will maintain the current node and the flag. The flag will be set to True if the children of the current node are not visited.

In Python, the stack can be implemented using a Python list.

  • Create a binary tree if it is not given
  • Add the root node in the stack (list)
  • While there is an element in the stack (list)
    • Read an element from the stack (node, flag).
    • If the flag is true, set the flag as false. Add right and left children to the stack.
    • Else, print the value of the current node. Pop the node from the stack (Remove the last element from the list).

If you understand the logic and algorithm, you can implement it in many programming languages like C/C++, Java, Python…

Python Program for PostOrder Traversal without Recursion:

#structure/class for a node
#by defult, left and right pointers are None 
class node:
  def __init__(self, val, left=None, right=None):
    self.left=left
    self.val=val
    self.right=right
 
 
#adding element in the binary tree
root=node(4)
root.left=node(1)
root.right=node(5)
root.left.left=node(7)
root.left.right=node(3)
root.right.right=node(6)


#return True if the node has child
#retun False if node has no child
def isChild(node):
    if node.right or node.left:
        return True
    else:
        return False


#print post order traversal
#without recursion
def printPostOrderWithoutRec(node):
    liNode = []
    if node:
        liNode.append([node, isChild(node)])
    else:
        print("Tree is empty.")
        return

    while liNode:
        curNode, bChild = liNode[-1]

        if bChild:
            liNode[-1][1] = 0
            if curNode.right:
                liNode.append([curNode.right, isChild(curNode.right)])
            if curNode.left:
                liNode.append([curNode.left, isChild(curNode.left)])
        else:
            print(curNode.val)
            del liNode[-1]


printPostOrderWithoutRec(root)

Output:

7
3
1
6
5
4

What’s Next:

I hope you understood postorder traversal without recursion. You can practice implementing inorder and preorder traversal without recursion.

If you are preparing for an interview with product-based companies, you have to prepare for a binary tree. If you have any queries, you can comment below.

Binary Treecoding challenge
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Leave a Reply Cancel reply

Why?

Why Competitive Programming Important?

Coding Challenges for Practice

  1. Count Common Factor
  2. Does it Divide
  3. Sum of Sub Arrays
  4. Pair of Desired Sum
  5. Remove Duplicate Char from String
  6. Sort String by Char Freq (Python)
  7. Sort String by Char Freq (Java)
  8. Split Array into Equal Sum Subarray
  9. Validate IP Address
  10. Validate PAN Card Number
  11. Validate Sudoku
  12. Sort Circular Rotated Array
  13. Min Arrow to Burst Bubbles
  14. Min Cost to Paint All Houses [Amazon]
  15. HourGlass with Largest Sum
  16. Max Profit by Buying/Selling Stocks
  17. Hailstone Sequence
  18. Reverse String without affecting Special Characters
  19. Secure Conversation by Encry/Decry
  20. Special Elements in Matrix
  21. Next Greater No with Same set of Digits
  22. Smallest Subarray with Sum Greater than Given Number
  23. Group Anagrams
  24. Find Duplicates in Array in O(n)
  25. Find Two Unique Numbers from Array in O(n)
  26. Number Patterns & Finding Smallest Number
  27. First Unique Element in a Stream
  28. Flip Equivalent Binary Trees [TeachMint]
  29. Minimum Cost of Merging Files [Amazon]
  30. Minimum Distance for Truck to Deliver Order [Amazon]
  31. Order Task for Given Dependencies
  32. Design Music Player
  33. Multilevel Parking System Design
  34. Minimum Coins Required
  35. Max Sum Subarray
  36. Max Avg Sum of Two Subsequences
  37. Merge Overlapping Intervals
  38. Longest Balanced Subarray
  39. Longest Path in a Weighted Tree
  40. Generate Balanced Parentheses
  41. PostOrder Traversal Without Recursion

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard