![]() |
VOOZH | about |
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 1Input:
👁 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.
Below is the implementation of the above approach:
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)