![]() |
VOOZH | about |
Given a binary tree, write an iterative function to print the Preorder traversal of the tree. The Preorder traversal follows the order: Root → Left → Right.
Examples:
Input:
1
/ \
2 3
/ \
4 5
Output: 1 2 4 5 3
Explanation: Preorder traversal (Root->Left->Right) of the tree is 1 2 4 5 3.Input:
8
/ \
1 5
\ / \
7 10 6
\ /
10 6
Output: 8 1 7 10 5 10 6 6
Explanation:
Preorder traversal (Root->Left->Right) of the tree is 8 1 7 10 5 10 6 6.
Table of Content
Following is a simple stack based iterative process to print Preorder traversal.
- Create an empty stack and push root node to stack.
- Do the following while is not empty.
- Pop an item from the stack and print it.
- Push right child of a popped item to stack
- Push left child of a popped item to stack
The right child is pushed before the left child to make sure that the left subtree is processed first.
1 2 4 5 3
In the previous solution we can see that the left child is popped as soon as it is pushed to the stack, therefore it is not required to push it into the stack.
The idea is to start traversing the tree from the root node and keep printing the left child while exists and simultaneously, push the right child of every node in an auxiliary stack. Once we reach a null node, pop a right child from the auxiliary stack and repeat the process while the auxiliary stack is not empty.
1 2 4 5 3
Morris Traversal is a tree traversal technique that allows you to traverse a binary tree without using recursion or a stack. The Preorder Morris Traversal algorithm works by manipulating the tree's pointers, specifically by utilizing the inorder predecessor of each node.
Algorithm for Preorder Morris Traversal:
1. If the left child of the current node is NULL:
2. If the left child of the current node is NOT NULL:
Two cases arise:
a) The right child of the inorder predecessor already points to the current node:
b) The right child of the inorder predecessor is NULL:
3. Repeat the process until the current node is NULL.
1 2 4 5 3
Refer Preorder Traversal of Binary Tree for recursive code