Given a Binary Tree, write an iterative function to print Preorder traversal of the given binary tree.
Refer this for recursive preorder traversal of Binary Tree. To convert an inherently recursive procedures to iterative, we need an explicit stack. Following is a simple stack based iterative process to print Preorder traversal.
1) Create an empty stack nodeStack and push root node to stack.
2) Do following while nodeStack is not empty.
….a) Pop an item from stack and print it.
….b) Push right child of popped item to stack
….c) Push left child of popped item to stack
Right child is pushed before left child to make sure that left subtree is processed first.
10 8 3 5 2 2
This article is compiled by Saurabh Sharma and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Iterative Preorder Traversal of an N-ary Tree
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Find postorder traversal of BST from preorder traversal
- Construct BST from given preorder traversal | Set 1
- Construct BST from given preorder traversal | Set 2
- Morris traversal for Preorder
- Preorder Traversal of N-ary Tree Without Recursion
- Construct a special tree from given preorder traversal
- Construct the full k-ary tree from its preorder traversal
- Print Postorder traversal from given Inorder and Preorder traversals
- Find n-th node in Preorder traversal of a Binary Tree
- Number of elements smaller than root using preorder traversal of a BST
- Modify a binary tree to get preorder traversal using right pointers only
- Check if a given array can represent Preorder Traversal of Binary Search Tree
- Iterative Postorder Traversal | Set 2 (Using One Stack)