Iterative Preorder Traversal

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
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
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
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++
Java
Python3
C#
Javascript
// C++ program to implement iterative preorder traversal#include <bits/stdc++.h> using namespace std; /* A binary tree node has data, left child and right child */struct node {    int data;    struct node* left;    struct node* right;}; /* Helper function that allocates a new node with the given data and   NULL left and right  pointers.*/struct node* newNode(int data){    struct node* node = new struct node;    node->data = data;    node->left = NULL;    node->right = NULL;    return (node);} // An iterative process to print preorder traversal of Binary treevoid iterativePreorder(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        struct node* 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 functionsint main(){    /* Constructed binary tree is            10          /   \        8      2      /  \    /    3     5  2  */    struct node* 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);    return 0;}
// Java program to implement iterative preorder traversalimport java.util.Stack; // A binary tree nodeclass Node {     int data;    Node left, right;     Node(int item)    {        data = item;        left = right = null;    }} class BinaryTree {     Node root;     void iterativePreorder()    {        iterativePreorder(root);    }     // An iterative process to print preorder traversal of Binary tree    void iterativePreorder(Node node)    {         // Base Case        if (node == null) {            return;        }         // Create an empty stack and push root to it        Stack<Node> nodeStack = new Stack<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    public static void main(String args[])    {        BinaryTree tree = new BinaryTree();        tree.root = new Node(10);        tree.root.left = new Node(8);        tree.root.right = new Node(2);        tree.root.left.left = new Node(3);        tree.root.left.right = new Node(5);        tree.root.right.left = new Node(2);        tree.iterativePreorder();    }} // This code has been contributed by Mayank Jaiswal
# Python program to perform iterative preorder traversal # A binary tree nodeclass Node:     # 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 traversal of BTdef iterativePreorder(root):         # Base CAse    if root is None:        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()        print (node.data, end=" ")                 # Push right and left children of the popped node        # to stack        if node.right is not None:            nodeStack.append(node.right)        if node.left is not None:            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# program to implement iterative// preorder traversalusing System;using System.Collections.Generic; // A binary tree nodepublic class Node {    public int data;    public Node left, right;     public Node(int item)    {        data = item;        left = right = null;    }} class GFG {    public Node root;     public virtual void iterativePreorder()    {        iterativePreorder(root);    }     // An iterative process to print preorder    // traversal of Binary tree    public virtual void iterativePreorder(Node node)    {         // Base Case        if (node == null) {            return;        }         // Create an empty stack and push root to it        Stack<Node> nodeStack = new Stack<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    public static void Main(string[] args)    {        GFG tree = new GFG();        tree.root = new Node(10);        tree.root.left = new Node(8);        tree.root.right = new Node(2);        tree.root.left.left = new Node(3);        tree.root.left.right = new Node(5);        tree.root.right.left = new Node(2);        tree.iterativePreorder();    }} // This code is contributed by Shrikant13
<script>  // Javascript program to implement iterative// preorder traversal // A binary tree nodeclass Node{    constructor(item)    {        this.data = item;        this.left = null;        this.right = null;    }} var root = null; // An iterative process to print preorder// traversal of Binary treefunction iterativePreorder(node){         // Base Case    if (node == null)    {        return;    }         // Create an empty stack and push root to it    var 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.length > 0)    {                 // Pop the top item from stack and print it        var mynode = nodeStack[nodeStack.length - 1];        document.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 Coderoot = new Node(10);root.left = new Node(8);root.right = new Node(2);root.left.left = new Node(3);root.left.right = new Node(5);root.right.left = new Node(2); iterativePreorder(root); // This code is contributed by itsok </script>
10 8 3 5 2 2
 
Time Complexity: O(N) Auxiliary Space: O(H), where H is the height of the tree.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
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++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // Tree Nodestruct Node {    int data;    Node *left, *right;     Node(int data)    {        this->data = data;        this->left = this->right = NULL;    }}; // Iterative function to do Preorder traversal of the treevoid preorderIterative(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 Codeint main(){    Node* root = new Node(10);    root->left = new Node(20);    root->right = new Node(30);    root->left->left = new Node(40);    root->left->left->left = new Node(70);    root->left->right = new Node(50);    root->right->left = new Node(60);    root->left->left->right = new Node(80);     preorderIterative(root);     return 0;}
import java.util.Stack; // A binary tree nodeclass Node{    int data;    Node left, right;     Node(int item)    {        data = item;        left = right = null;    }} class BinaryTree{ Node root; void preorderIterative(){    preorderIterative(root);} // Iterative function to do Preorder// traversal of the treevoid preorderIterative(Node node){    if (node == null)    {        return;    }     Stack<Node> st = new Stack<Node>();         // Start from root node (set curr    // node to root node)    Node curr = node;         // Run till stack is not empty or    // current is not NULL    while (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 stack        if (!st.isEmpty())        {            curr = st.pop();        }    }} // Driver codepublic static void main(String args[]){    BinaryTree tree = new BinaryTree();         tree.root = new Node(10);    tree.root.left = new Node(20);    tree.root.right = new Node(30);    tree.root.left.left = new Node(40);    tree.root.left.left.left = new Node(70);    tree.root.left.right = new Node(50);    tree.root.right.left = new Node(60);    tree.root.left.left.right = new Node(80);         tree.preorderIterative();}} // This code is contributed by Vivek Singh Bhadauria
# Tree Nodeclass Node:     def __init__(self, data = 0):        self.data = data        self.left = None        self.right = None     # Iterative function to do Preorder traversal of the treedef preorderIterative(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) or curr != 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
using System;using System.Collections.Generic; // A binary tree nodepublic class Node{    public int data;    public Node left, right;     public Node(int item)    {        data = item;        left = right = null;    }} public class BinaryTree{ Node root; void preorderIterative(){    preorderIterative(root);} // Iterative function to do Preorder// traversal of the treevoid preorderIterative(Node node){    if (node == null)    {        return;    }     Stack<Node> st = new Stack<Node>();         // Start from root node (set curr    // node to root node)    Node curr = node;         // Run till stack is not empty or    // current is not NULL    while (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 stack        if (st.Count != 0)        {            curr = st.Pop();        }    }} // Driver codepublic static void Main(String []args){    BinaryTree tree = new BinaryTree();         tree.root = new Node(10);    tree.root.left = new Node(20);    tree.root.right = new Node(30);    tree.root.left.left = new Node(40);    tree.root.left.left.left = new Node(70);    tree.root.left.right = new Node(50);    tree.root.right.left = new Node(60);    tree.root.left.left.right = new Node(80);         tree.preorderIterative();}} // This code is contributed by Amit Katiyar
<script> class Node{    constructor(item)    {        this.left = null;        this.right = null;        this.data = item;    }} let root; // Iterative function to do Preorder// traversal of the treefunction preorderiterative(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 NULL    while (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 stack        if (st.length > 0)        {            curr = st.pop();        }    }} function preorderIterative(){    preorderiterative(root);} // Driver coderoot = new Node(10);root.left = new Node(20);root.right = new Node(30);root.left.left = new Node(40);root.left.left.left = new Node(70);root.left.right = new Node(50);root.right.left = new Node(60);root.left.left.right = new Node(80);  preorderIterative(); // This code is contributed by decode2207 </script>
10 20 40 70 80 50 30 60
 
Time Complexity: O(N) Auxiliary Space: O(H), where H is the height of the tree.
shrikanth13
andrew1234
vivek singh bhadauri
amit143katiyar
user282
itsok
decode2207
surinderdawra388
amartyaghoshgfg
dhairya bhardwaj
hardikkoriintern
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
A program to check if a binary tree is BST or not
Decision Tree
Top 50 Tree Coding Problems for Interviews
Segment Tree | Set 1 (Sum of given range)
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Sorted Array to Balanced BST