Iterative Preorder Traversal

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.

C++

filter_none

editclose

play_arrow

linkbrightness_4code

#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 and

NULL 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 tree

voiditerativePreorder(node *root)

{

// Base Case

if(root == NULL)

return;

// Create an empty stack and push root to it

stack<node *> nodeStack;

nodeStack.push(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(nodeStack.empty() == false)

{

// Pop the top item from stack and print it

structnode *node = nodeStack.top();

printf("%d ", node->data);

nodeStack.pop();

// Push right and left children of the popped node to stack

if(node->right)

nodeStack.push(node->right);

if(node->left)

nodeStack.push(node->left);

}

}

// Driver program to test above functions

intmain()

{

/* Constructed binary tree is

10

/ \

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;

}

chevron_right

filter_none

Java

filter_none

editclose

play_arrow

linkbrightness_4code

// Java program to implement iterative preorder traversal

importjava.util.Stack;

// A binary tree node

classNode {

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 tree

voiditerativePreorder(Node node) {

// Base Case

if(node == null) {

return;

}

// Create an empty stack and push root to it

Stack<Node> nodeStack = newStack<Node>();

nodeStack.push(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(nodeStack.empty() == false) {

// Pop the top item from stack and print it

Node mynode = nodeStack.peek();

System.out.print(mynode.data + " ");

nodeStack.pop();

// Push right and left children of the popped node to stack

if(mynode.right != null) {

nodeStack.push(mynode.right);

}

if(mynode.left != null) {

nodeStack.push(mynode.left);

}

}

}

// driver program to test above functions

publicstaticvoidmain(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 Jaiswal

chevron_right

filter_none

Python

filter_none

editclose

play_arrow

linkbrightness_4code

# Python program to perform iterative preorder traversal

# A binary tree node

classNode:

# Constructor to create a new node

def__init__(self, data):

self.data =data

self.left =None

self.right =None

# An iterative process to print preorder traveral of BT

defiterativePreorder(root):

# Base CAse

ifroot isNone:

return

# create an empty stack and push root to it

nodeStack =[]

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 it

node =nodeStack.pop()

printnode.data,

# Push right and left children of the popped node

# to stack

ifnode.right isnotNone:

nodeStack.append(node.right)

ifnode.left isnotNone:

nodeStack.append(node.left)

# Driver program to test above function

root =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)

chevron_right

filter_none

C#

filter_none

editclose

play_arrow

linkbrightness_4code

// C# program to implement iterative

// preorder traversal

usingSystem;

usingSystem.Collections.Generic;

// A binary tree node

publicclassNode

{

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 tree

publicvirtualvoiditerativePreorder(Node node)

{

// Base Case

if(node == null)

{

return;

}

// Create an empty stack and push root to it

Stack<Node> nodeStack = newStack<Node>();

nodeStack.Push(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(nodeStack.Count > 0)

{

// Pop the top item from stack and print it

Node mynode = nodeStack.Peek();

Console.Write(mynode.data + " ");

nodeStack.Pop();

// Push right and left children of

// the popped node to stack

if(mynode.right != null)

{

nodeStack.Push(mynode.right);

}

if(mynode.left != null)

{

nodeStack.Push(mynode.left);

}

}

}

// Driver Code

publicstaticvoidMain(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 Shrikant13

chevron_right

filter_none

Output:

10 8 3 5 2 2

Time Complexity: O(N)Auxiliary Space: O(N), where N is the total number of nodes in the tree.

Space Optimized Solution: The idea is to start traversing the tree from root node, and keep printing the left child while exists and simultaneously, push 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.

Below is the implementation of the above approach:

C++

filter_none

editclose

play_arrow

linkbrightness_4code

#include <bits/stdc++.h>

usingnamespacestd;

// Tree Node

structNode

{

intdata;

Node *left, *right;

Node(intdata)

{

this->data = data;

this->left = this->right = NULL;

}

};

// Iterative function to do Preorder traversal of the tree

voidpreorderIterative(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 NULL

while(!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 stack

if(st.empty() == false)

{

curr = st.top();

st.pop();

}

}

}

// Driver Code

intmain()

{

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;

}

chevron_right

filter_none

Python

filter_none

editclose

play_arrow

linkbrightness_4code

# Tree Node

classNode:

def__init__(self, data =0):

self.data =data

self.left =None

self.right =None

# Iterative function to do Preorder traversal of the tree

defpreorderIterative(root):

if(root ==None):

return

st =[]

# start from root node (set current node to root node)

curr =root

# run till stack is not empty or current is

# not NULL

while(len(st) orcurr !=None):

# Print left children while exist

# and keep appending right into the

# stack.

while(curr !=None):

print(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 stack

if(len(st) > 0):

curr =st[-1]

st.pop()

# Driver Code

root =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 Kundu

chevron_right

filter_none

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.

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

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details