Iterative Preorder Traversal
- Difficulty Level : Easy
- Last Updated : 17 Jun, 2022
Given a Binary Tree, write an iterative function to print the Preorder traversal of the given binary tree.
Refer to this for recursive preorder traversal of Binary Tree. To convert an inherently recursive procedure to iterative, we need an explicit stack.
Following is a simple stack based iterative process to print Preorder traversal.
![]()
- Create an empty stack nodeStack and push root node to stack.
- Do the following while nodeStack 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.
C++
// C++ program to implement iterative preorder traversal#include <bits/stdc++.h>usingnamespacestd;/* A binary tree node has data, left child and right child */structnode {intdata;structnode* left;structnode* right;};/* Helper function that allocates a new node with the given data andNULL left and right pointers.*/structnode* newNode(intdata){structnode* node =newstructnode;node->data = data;node->left = NULL;node->right = NULL;return(node);}// An iterative process to print preorder traversal of Binary treevoiditerativePreorder(node* root){// Base Caseif(root == NULL)return;// Create an empty stack and push root to itstack<node*> nodeStack;nodeStack.push(root);/* Pop all items one by one. Do following for every popped itema) print itb) push its right childc) push its left childNote that right child is pushed first so that left is processed first */while(nodeStack.empty() ==false) {// Pop the top item from stack and print itstructnode* node = nodeStack.top();printf("%d ", node->data);nodeStack.pop();// Push right and left children of the popped node to stackif(node->right)nodeStack.push(node->right);if(node->left)nodeStack.push(node->left);}}// Driver program to test above functionsintmain(){/* Constructed binary tree is10/ \8 2/ \ /3 5 2*/structnode* root = newNode(10);root->left = newNode(8);root->right = newNode(2);root->left->left = newNode(3);root->left->right = newNode(5);root->right->left = newNode(2);iterativePreorder(root);return0;}Java
// Java program to implement iterative preorder traversalimportjava.util.Stack;// A binary tree nodeclassNode {intdata;Node left, right;Node(intitem){data = item;left = right =null;}}classBinaryTree {Node root;voiditerativePreorder(){iterativePreorder(root);}// An iterative process to print preorder traversal of Binary treevoiditerativePreorder(Node node){// Base Caseif(node ==null) {return;}// Create an empty stack and push root to itStack<Node> nodeStack =newStack<Node>();nodeStack.push(root);/* Pop all items one by one. Do following for every popped itema) print itb) push its right childc) push its left childNote that right child is pushed first so that left is processed first */while(nodeStack.empty() ==false) {// Pop the top item from stack and print itNode mynode = nodeStack.peek();System.out.print(mynode.data +" ");nodeStack.pop();// Push right and left children of the popped node to stackif(mynode.right !=null) {nodeStack.push(mynode.right);}if(mynode.left !=null) {nodeStack.push(mynode.left);}}}// driver program to test above functionspublicstaticvoidmain(String args[]){BinaryTree tree =newBinaryTree();tree.root =newNode(10);tree.root.left =newNode(8);tree.root.right =newNode(2);tree.root.left.left =newNode(3);tree.root.left.right =newNode(5);tree.root.right.left =newNode(2);tree.iterativePreorder();}}// This code has been contributed by Mayank JaiswalPython3
# Python program to perform iterative preorder traversal# A binary tree nodeclassNode:# Constructor to create a new nodedef__init__(self, data):self.data=dataself.left=Noneself.right=None# An iterative process to print preorder traversal of BTdefiterativePreorder(root):# Base CAseifrootisNone:return# create an empty stack and push root to itnodeStack=[]nodeStack.append(root)# Pop all items one by one. Do following for every popped item# a) print it# b) push its right child# c) push its left child# Note that right child is pushed first so that left# is processed first */while(len(nodeStack) >0):# Pop the top item from stack and print itnode=nodeStack.pop()(node.data, end=" ")# Push right and left children of the popped node# to stackifnode.rightisnotNone:nodeStack.append(node.right)ifnode.leftisnotNone:nodeStack.append(node.left)# Driver program to test above functionroot=Node(10)root.left=Node(8)root.right=Node(2)root.left.left=Node(3)root.left.right=Node(5)root.right.left=Node(2)iterativePreorder(root)# This code is contributed by Nikhil Kumar Singh(nickzuck_007)C#
// C# program to implement iterative// preorder traversalusingSystem;usingSystem.Collections.Generic;// A binary tree nodepublicclassNode {publicintdata;publicNode left, right;publicNode(intitem){data = item;left = right =null;}}classGFG {publicNode root;publicvirtualvoiditerativePreorder(){iterativePreorder(root);}// An iterative process to print preorder// traversal of Binary treepublicvirtualvoiditerativePreorder(Node node){// Base Caseif(node ==null) {return;}// Create an empty stack and push root to itStack<Node> nodeStack =newStack<Node>();nodeStack.Push(root);/* Pop all items one by one. Do followingfor every popped itema) print itb) push its right childc) push its left childNote that right child is pushed first sothat left is processed first */while(nodeStack.Count > 0) {// Pop the top item from stack and print itNode mynode = nodeStack.Peek();Console.Write(mynode.data +" ");nodeStack.Pop();// Push right and left children of// the popped node to stackif(mynode.right !=null) {nodeStack.Push(mynode.right);}if(mynode.left !=null) {nodeStack.Push(mynode.left);}}}// Driver CodepublicstaticvoidMain(string[] args){GFG tree =newGFG();tree.root =newNode(10);tree.root.left =newNode(8);tree.root.right =newNode(2);tree.root.left.left =newNode(3);tree.root.left.right =newNode(5);tree.root.right.left =newNode(2);tree.iterativePreorder();}}// This code is contributed by Shrikant13Javascript
<script>// Javascript program to implement iterative// preorder traversal// A binary tree nodeclass Node{constructor(item){this.data = item;this.left =null;this.right =null;}}varroot =null;// An iterative process to print preorder// traversal of Binary treefunctioniterativePreorder(node){// Base Caseif(node ==null){return;}// Create an empty stack and push root to itvarnodeStack = [];nodeStack.push(root);/* Pop all items one by one. Do followingfor every popped itema) print itb) push its right childc) push its left childNote that right child is pushed first sothat left is processed first */while(nodeStack.length > 0){// Pop the top item from stack and print itvarmynode = nodeStack[nodeStack.length - 1];document.write(mynode.data +" ");nodeStack.pop();// Push right and left children of// the popped node to stackif(mynode.right !=null){nodeStack.push(mynode.right);}if(mynode.left !=null){nodeStack.push(mynode.left);}}}// Driver Coderoot =newNode(10);root.left =newNode(8);root.right =newNode(2);root.left.left =newNode(3);root.left.right =newNode(5);root.right.left =newNode(2);iterativePreorder(root);// This code is contributed by itsok</script>Output:10 8 3 5 2 2
Time Complexity: O(N)
Auxiliary Space: O(H), where H is the height of the tree.Another Solution: 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.
This is a micro-optimization over the previous approach, both the solutions use asymptotically similar auxiliary space.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>usingnamespacestd;// Tree NodestructNode {intdata;Node *left, *right;Node(intdata){this->data = data;this->left =this->right = NULL;}};// Iterative function to do Preorder traversal of the treevoidpreorderIterative(Node* root){if(root == NULL)return;stack<Node*> st;// start from root node (set current node to root node)Node* curr = root;// run till stack is not empty or current is// not NULLwhile(!st.empty() || curr != NULL) {// Print left children while exist// and keep pushing right into the// stack.while(curr != NULL) {cout << curr->data <<" ";if(curr->right)st.push(curr->right);curr = curr->left;}// We reach when curr is NULL, so We// take out a right child from stackif(st.empty() ==false) {curr = st.top();st.pop();}}}// Driver Codeintmain(){Node* root =newNode(10);root->left =newNode(20);root->right =newNode(30);root->left->left =newNode(40);root->left->left->left =newNode(70);root->left->right =newNode(50);root->right->left =newNode(60);root->left->left->right =newNode(80);preorderIterative(root);return0;}Java
importjava.util.Stack;// A binary tree nodeclassNode{intdata;Node left, right;Node(intitem){data = item;left = right =null;}}classBinaryTree{Node root;voidpreorderIterative(){preorderIterative(root);}// Iterative function to do Preorder// traversal of the treevoidpreorderIterative(Node node){if(node ==null){return;}Stack<Node> st =newStack<Node>();// Start from root node (set curr// node to root node)Node curr = node;// Run till stack is not empty or// current is not NULLwhile(curr !=null|| !st.isEmpty()){// Print left children while exist// and keep pushing right into the// stack.while(curr !=null){System.out.print(curr.data +" ");if(curr.right !=null)st.push(curr.right);curr = curr.left;}// We reach when curr is NULL, so We// take out a right child from stackif(!st.isEmpty()){curr = st.pop();}}}// Driver codepublicstaticvoidmain(String args[]){BinaryTree tree =newBinaryTree();tree.root =newNode(10);tree.root.left =newNode(20);tree.root.right =newNode(30);tree.root.left.left =newNode(40);tree.root.left.left.left =newNode(70);tree.root.left.right =newNode(50);tree.root.right.left =newNode(60);tree.root.left.left.right =newNode(80);tree.preorderIterative();}}// This code is contributed by Vivek Singh BhadauriaPython3
# Tree NodeclassNode:def__init__(self, data=0):self.data=dataself.left=Noneself.right=None# Iterative function to do Preorder traversal of the treedefpreorderIterative(root):if(root==None):returnst=[]# start from root node (set current node to root node)curr=root# run till stack is not empty or current is# not NULLwhile(len(st)orcurr !=None):# Print left children while exist# and keep appending right into the# stack.while(curr !=None):(curr.data, end=" ")if(curr.right !=None):st.append(curr.right)curr=curr.left# We reach when curr is NULL, so We# take out a right child from stackif(len(st) >0):curr=st[-1]st.pop()# Driver Coderoot=Node(10)root.left=Node(20)root.right=Node(30)root.left.left=Node(40)root.left.left.left=Node(70)root.left.right=Node(50)root.right.left=Node(60)root.left.left.right=Node(80)preorderIterative(root)# This code is contributed by Arnab KunduC#
usingSystem;usingSystem.Collections.Generic;// A binary tree nodepublicclassNode{publicintdata;publicNode left, right;publicNode(intitem){data = item;left = right =null;}}publicclassBinaryTree{Node root;voidpreorderIterative(){preorderIterative(root);}// Iterative function to do Preorder// traversal of the treevoidpreorderIterative(Node node){if(node ==null){return;}Stack<Node> st =newStack<Node>();// Start from root node (set curr// node to root node)Node curr = node;// Run till stack is not empty or// current is not NULLwhile(curr !=null|| st.Count!=0){// Print left children while exist// and keep pushing right into the// stack.while(curr !=null){Console.Write(curr.data +" ");if(curr.right !=null)st.Push(curr.right);curr = curr.left;}// We reach when curr is NULL, so We// take out a right child from stackif(st.Count != 0){curr = st.Pop();}}}// Driver codepublicstaticvoidMain(String []args){BinaryTree tree =newBinaryTree();tree.root =newNode(10);tree.root.left =newNode(20);tree.root.right =newNode(30);tree.root.left.left =newNode(40);tree.root.left.left.left =newNode(70);tree.root.left.right =newNode(50);tree.root.right.left =newNode(60);tree.root.left.left.right =newNode(80);tree.preorderIterative();}}// This code is contributed by Amit KatiyarJavascript
<script>class Node{constructor(item){this.left =null;this.right =null;this.data = item;}}let root;// Iterative function to do Preorder// traversal of the treefunctionpreorderiterative(node){if(node ==null){return;}let st = [];// Start from root node (set curr// node to root node)let curr = node;// Run till stack is not empty or// current is not NULLwhile(curr !=null|| st.length > 0){// Print left children while exist// and keep pushing right into the// stack.while(curr !=null){document.write(curr.data +" ");if(curr.right !=null)st.push(curr.right);curr = curr.left;}// We reach when curr is NULL, so We// take out a right child from stackif(st.length > 0){curr = st.pop();}}}functionpreorderIterative(){preorderiterative(root);}// Driver coderoot =newNode(10);root.left =newNode(20);root.right =newNode(30);root.left.left =newNode(40);root.left.left.left =newNode(70);root.left.right =newNode(50);root.right.left =newNode(60);root.left.left.right =newNode(80);preorderIterative();// This code is contributed by decode2207</script>Output:10 20 40 70 80 50 30 60
Time Complexity: O(N)
Auxiliary Space: O(H), where H is the height of the tree.My Personal Notes arrow_drop_upRecommended ArticlesPage :Article Contributed By :Improved By :Article Tags :Practice Tags :



