VOOZH about

URL: https://www.geeksforgeeks.org/dsa/preorder-postorder-and-inorder-traversal-of-a-binary-tree-using-a-single-stack/

⇱ Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack

Last Updated : 23 Jul, 2025

Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal.

Examples:

Input:

👁 Image

Output:
Preorder Traversal: 1 2 3
Inorder Traversal: 2 1 3
Postorder Traversal: 2 3 1

Input:

👁 Image

Output:
Preorder traversal: 1 2 4 5 3 6 7
Inorder traversal: 4 2 5 1 6 3 7
Post-order traversal: 4 5 2 6 7 3 1

Approach: The problem can be solved using only one stack. The idea is to mark each node of the binary tree by assigning a value, called status code with each node such that value 1 represents that the node is currently visiting in preorder traversal, value 2 represents the nodes is currently visiting in inorder traversal and value 3 represents the node is visiting in the postorder traversal.

  • Initialize a stack < pair < Node*, int>> say S.
  • Push the root node in the stack with status as 1, i.e {root, 1}.
  • Initialize three vectors of integers say preorder, inorder, and postorder.
  • Traverse the stack until the stack is empty and check for the following conditions:
    • If the status of the top node of the stack is 1 then update the status of the top node of the stack to 2 and push the top node in the vector preorder and insert the left child of the top node if it is not NULL in the stack S.
    • If the status of the top node of the stack is 2 then update the status of the top node of the stack to 3 and push the top node in the vector inorder and insert the right child of the top node if it is not NULL in the stack S.
    • If the status of the top node of the stack is 3 then push the top node in vector postorder and then pop the top element.
  • Finally, print vectors preorder, inorder, and postorder.

Below is the implementation of the above approach:


Output: 
Preorder Traversal: 1 2 4 5 3 6 7 
Inorder Traversal: 4 2 5 1 6 3 7 
Postorder Traversal: 4 5 2 6 7 3 1

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment