The Wayback Machine - https://web.archive.org/web/20241116003438/https://www.geeksforgeeks.org/iterative-preorder-traversal/
Open In App

Iterative Preorder Traversal

Last Updated : 22 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

  1. Create an empty stack nodeStack and push root node to stack. 
  2. Do the following while nodeStack is not empty. 
    1. Pop an item from the stack and print it. 
    2. Push right child of a popped item to stack 
    3. 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>

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 tree
void 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 functions
int 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
// Java program to implement iterative preorder traversal
import java.util.Stack;

// A binary tree node
class 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
# Python program to perform iterative preorder traversal

# A binary tree node
class 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 BT
def 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 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)
C#
// C# program to implement iterative
// preorder traversal
using System;
using System.Collections.Generic;

// A binary tree node
public 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
JavaScript
 
// Javascript program to implement iterative
// preorder traversal

// A binary tree node
class Node
{
    constructor(item)
    {
        this.data = item;
        this.left = null;
        this.right = null;
    }
}

var root = null;

// An iterative process to print preorder
// traversal of Binary tree
function 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 Code
root = 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

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>
using namespace std;

// Tree Node
struct 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 tree
void 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 Code
int 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;
}
Java
import java.util.Stack;

// A binary tree node
class 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 tree 
void 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 code
public 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
Python
# Tree Node
class Node:

    def __init__(self, data = 0):
        self.data = data
        self.left = None
        self.right = None
    
# Iterative function to do Preorder traversal of the tree
def 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
C#
using System;
using System.Collections.Generic;

// A binary tree node
public 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 tree 
void 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 code
public 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 
JavaScript
class Node
{
    constructor(item) 
    {
        this.left = null;
        this.right = null;
        this.data = item;
    }
}

let root;

// Iterative function to do Preorder
// traversal of the tree
function 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 code
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();

// This code is contributed by decode2207 

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.

ANOTHER APPROACH:

Intuition:

Using Morris Traversal, we can traverse the tree without using stack and recursion. The algorithm for Preorder is almost similar to Morris traversal for Inorder.

1…If left child is null, print the current node data. Move to right child. 
….Else, Make the right child of the inorder predecessor point to the current node. Two cases arise: 
………a) The right child of the inorder predecessor already points to the current node. Set right child to NULL. Move to right child of current node. 
………b) The right child is NULL. Set it to the current node. Print the current node’s data and move to left child of current node. 
2…Iterate until the current node is not NULL.

Implementation:

C++
// C++ code for this approach
#include <iostream>

using namespace std;

// A binary tree node
class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int item) {
        data = item;
        left = right = NULL;
    }
};

class BinaryTree {
public:
    Node* root;

    void morrisTraversalPreorder() {
        morrisTraversalPreorder(root);
    }

    // Preorder traversal without recursion and without stack
    void morrisTraversalPreorder(Node* node) {
        while (node != NULL) {
            // If left child is null, print the current node data. Move to the right child.
            if (node->left == NULL) {
                cout << node->data << " ";
                node = node->right;
            } else {
                // Find the inorder predecessor
                Node* current = node->left;
                while (current->right != NULL && current->right != node) {
                    current = current->right;
                }

                // If the right child of the inorder predecessor already points to this node
                if (current->right == node) {
                    current->right = NULL;
                    node = node->right;
                } else {
                    cout << node->data << " ";
                    current->right = node;
                    node = node->left;
                }
            }
        }
    }

    void preorder() {
        preorder(root);
    }

    // Function for Standard preorder traversal
    void preorder(Node* node) {
        if (node != NULL) {
            cout << node->data << " ";
            preorder(node->left);
            preorder(node->right);
        }
    }
};

// Driver program to test the above functions
int main() {
    BinaryTree tree;
    tree.root = new Node(1);
    tree.root->left = new Node(2);
    tree.root->right = new Node(3);
    tree.root->left->left = new Node(4);
    tree.root->left->right = new Node(5);
    tree.root->right->left = new Node(6);
    tree.root->right->right = new Node(7);
    tree.root->left->left->left = new Node(8);
    tree.root->left->left->right = new Node(9);
    tree.root->left->right->left = new Node(10);
    tree.root->left->right->right = new Node(11);
    tree.morrisTraversalPreorder();
    cout << endl;
    tree.preorder();
    return 0;
}

// This code is contributed by guptapratik
Java
// Java program to implement Morris preorder traversal

// A binary tree node
class Node {

    int data;
    Node left, right;

    Node(int item)
    {
        data = item;
        left = right = null;
    }
}

class BinaryTree {

    Node root;

    void morrisTraversalPreorder()
    {
        morrisTraversalPreorder(root);
    }

    // Preorder traversal without recursion and without
    // stack
    void morrisTraversalPreorder(Node node)
    {
        while (node != null) {

            // If left child is null, print the current node
            // data. Move to right child.
            if (node.left == null) {
                System.out.print(node.data + " ");
                node = node.right;
            }
            else {

                // Find inorder predecessor
                Node current = node.left;
                while (current.right != null
                       && current.right != node) {
                    current = current.right;
                }

                // If the right child of inorder predecessor
                // already points to this node
                if (current.right == node) {
                    current.right = null;
                    node = node.right;
                }

                // If right child doesn't point to this
                // node, then print this node and make right
                // child point to this node
                else {
                    System.out.print(node.data + " ");
                    current.right = node;
                    node = node.left;
                }
            }
        }
    }

    void preorder() { preorder(root); }

    // Function for Standard preorder traversal
    void preorder(Node node)
    {
        if (node != null) {
            System.out.print(node.data + " ");
            preorder(node.left);
            preorder(node.right);
        }
    }

    // Driver programs to test above functions
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        tree.root.right.left = new Node(6);
        tree.root.right.right = new Node(7);
        tree.root.left.left.left = new Node(8);
        tree.root.left.left.right = new Node(9);
        tree.root.left.right.left = new Node(10);
        tree.root.left.right.right = new Node(11);
        tree.morrisTraversalPreorder();
        System.out.println("");
        tree.preorder();
    }
}

// this code has been contributed by Raunak Singh
Python
# Python3 program to implement Morris preorder traversal

# A binary tree node

class Node:
    def __init__(self, item):
        self.data = item
        self.left = self.right = None

class BinaryTree:
    def __init__(self):
        self.root = None

    def morris_traversal_preorder(self):
        self.morris_traversal_preorder_helper(self.root)

    # Preorder traversal without recursion and without stack
    def morris_traversal_preorder_helper(self, node):
        while node:
            # If left child is None, print the current 
            # node data. Move to the right child.
            if node.left is None:
                print(node.data, end=" ")
                node = node.right
            else:
                # Find inorder predecessor
                current = node.left
                while current.right is not None and current.right is not node:
                    current = current.right

                # If the right child of the inorder 
                # predecessor already points to this node
                if current.right is node:
                    current.right = None
                    node = node.right
                else:
                    # If the right child doesn't point to this node, 
                    # then print this node
                    # and make the right child point to this node
                    print(node.data, end=" ")
                    current.right = node
                    node = node.left

    def preorder(self):
        self.preorder_helper(self.root)

    # Function for standard preorder traversal
    def preorder_helper(self, node):
        if node is not None:
            print(node.data, end=" ")
            self.preorder_helper(node.left)
            self.preorder_helper(node.right)

# Driver program to test the above functions
tree = BinaryTree()
tree.root = Node(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
tree.root.left.left.left = Node(8)
tree.root.left.left.right = Node(9)
tree.root.left.right.left = Node(10)
tree.root.left.right.right = Node(11)

tree.morris_traversal_preorder()
print("")
tree.preorder()
C#
using System;

// A binary tree node
class Node
{
    public int data;
    public Node left, right;

    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}

class BinaryTree
{
    public Node root;

    public void morrisTraversalPreorder()
    {
        morrisTraversalPreorder(root);
    }

    // Preorder traversal without recursion and without
    // stack
    public void morrisTraversalPreorder(Node node)
    {
        while (node != null)
        {
            // If left child is null, print the current node
            // data. Move to right child.
            if (node.left == null)
            {
                Console.Write(node.data + " ");
                node = node.right;
            }
            else
            {
                // Find inorder predecessor
                Node current = node.left;
                while (current.right != null
                       && current.right != node)
                {
                    current = current.right;
                }

                // If the right child of the inorder predecessor
                // already points to this node
                if (current.right == node)
                {
                    current.right = null;
                    node = node.right;
                }
                // If the right child doesn't point to this
                // node, then print this node and make the right
                // child point to this node
                else
                {
                    Console.Write(node.data + " ");
                    current.right = node;
                    node = node.left;
                }
            }
        }
    }

    public void Preorder()
    {
        Preorder(root);
    }

    // Function for Standard preorder traversal
    public void Preorder(Node node)
    {
        if (node != null)
        {
            Console.Write(node.data + " ");
            Preorder(node.left);
            Preorder(node.right);
        }
    }

    // Driver programs to test the above functions
    public static void Main(string[] args)
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        tree.root.right.left = new Node(6);
        tree.root.right.right = new Node(7);
        tree.root.left.left.left = new Node(8);
        tree.root.left.left.right = new Node(9);
        tree.root.left.right.left = new Node(10);
        tree.root.left.right.right = new Node(11);
        tree.morrisTraversalPreorder();
        Console.WriteLine();
        tree.Preorder();
    }
}

// This code has been contributed by phasing17
JavaScript
class Node {
    constructor(item) {
        this.data = item;
        this.left = this.right = null;
    }
}

class BinaryTree {
    constructor() {
        this.root = null;
    }

    morrisTraversalPreorder() {
        this.morrisTraversalPreorderHelper(this.root);
    }

    // Preorder traversal without recursion and without stack
    morrisTraversalPreorderHelper(node) {
        while (node) {
            // If left child is null, print the current node data. Move to right child.
            if (node.left === null) {
                process.stdout.write(node.data + " ");
                node = node.right;
            } else {
                // Find inorder predecessor
                let current = node.left;
                while (current.right !== null && current.right !== node) {
                    current = current.right;
                }

                // If the right child of inorder predecessor already points to this node
                if (current.right === node) {
                    current.right = null;
                    node = node.right;
                } else {
                    // If right child doesn't point to this node, then print this node
                    // and make right child point to this node
                    process.stdout.write(node.data + " ");
                    current.right = node;
                    node = node.left;
                }
            }
        }
    }

    preorder() {
        this.preorderHelper(this.root);
    }

    // Function for Standard preorder traversal
    preorderHelper(node) {
        if (node !== null) {
            process.stdout.write(node.data + " ");
            this.preorderHelper(node.left);
            this.preorderHelper(node.right);
        }
    }
}

// Driver program to test above functions
const tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.left.left.left = new Node(8);
tree.root.left.left.right = new Node(9);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(11);
tree.morrisTraversalPreorder();
console.log("");
tree.preorder();

Output
1 2 4 8 9 5 10 11 3 6 7 
1 2 4 8 9 5 10 11 3 6 7 

Time Complexity: O(n), we visit every node at most once.
Auxiliary Space: O(1), we use a constant amount of space for variables and pointers.



Previous Article
Next Article

Similar Reads

Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, the task is to construct the binary tree using these two Preorder traversals. A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traversals. But we c
9 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Find postorder traversal of BST from preorder traversal
Given an array representing preorder traversal of BST, print its postorder traversal. Examples: Input : 40 30 35 80 100 Output : 35 30 100 80 40 Input : 40 30 32 35 80 90 100 120 Output : 35 32 30 120 100 90 80 40 Prerequisite: Construct BST from given preorder traversal Simple Approach: A simple solution is to first construct BST from a given preo
9 min read
Construct BST from given preorder traversal using Stack
Given preorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree. 10 / \ 5 40 / \ \ 1 7 50 We have discussed O(n^2) and O(n) recursive solutions in the previous post. Following is a stack based iterative solution that works in O(n) time
13 min read
Number of elements smaller than root using preorder traversal of a BST
Given a preorder traversal of a BST. The task is to find the number of elements less than root. Examples: Input: preorder[] = {3, 2, 1, 0, 5, 4, 6} Output: 3 Input: preorder[] = {5, 4, 3, 2, 1} Output: 4 For a binary search tree, a preorder traversal is of the form: root, { elements in left subtree of root }, { elements in right subtree of root } S
9 min read
Preorder Traversal of N-ary Tree Without Recursion
Given an n-ary tree, print preorder traversal of it. Example : Preorder traversal of below tree is A B K N M J F D G E C H I L The idea is to use stack like iterative preorder traversal of binary tree. Create an empty stack to store nodes. Push the root node to the stack. Run a loop while the stack is not empty Pop the top node from stack. Print th
7 min read
Find Leftmost and Rightmost node of BST from its given preorder traversal
Given a preorder sequence of the binary search tree of N nodes. The task is to find its leftmost and rightmost nodes. Examples: Input : N = 5, preorder[]={ 3, 2, 1, 5, 4 } Output : Leftmost = 1, Rightmost = 5 The BST constructed from this preorder sequence would be: 3 / \ 2 5 / / 1 4 Leftmost Node of this tree is equal to 1 Rightmost Node of this t
5 min read
Construct BST from given preorder traversal using Sorting
Given preorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree. 10 / \ 5 40 / \ \ 1 7 50 We have discussed methods to construct binary search tree in previous posts.Here is another method to construct binary search tree when given pre
10 min read
Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order tr
13 min read
Construct a Perfect Binary Tree from Preorder Traversal
Given an array pre[], representing the Preorder traversal of a Perfect Binary Tree consisting of N nodes, the task is to construct a Perfect Binary Tree from the given Preorder Traversal and return the root of the tree. Examples: Input: pre[] = {1, 2, 4, 5, 3, 6, 7}Output: 1 / \ / \ 2 3 / \ / \ / \ / \ 4 5 6 7 Input: pre[] = {1, 2, 3}Output: 1 / \
11 min read
Vertical Traversal of a Binary Tree using Preorder
Given a binary tree, print it vertically. The following examples illustrate the vertical order traversal.   Input:         1                  /    \                 2      3               / \   /   \             4   5  6   7                         /  \                        8    9  Output:  421 5 63 879 Brute Force Approach : O(n^2)We traverse th
15 min read
Construct BST from Preorder Traversal
Given the preorder traversal of a binary search tree, construct the BST. Examples: Input: {10, 5, 1, 7, 40, 50}Output: 10 / \ 5 40 / \ \ 1 7 50Explanation: The constructed tree is BST and if we do preorder traversal of it, we get the same array Input: {1, 2]Output: 1 \ 2 Input: {2, 1]Output: 2 / 1 Table of Content Naive - One by One Insert Better -
15+ min read
Construct the full k-ary tree from its preorder traversal
Given an array that contains the preorder traversal of the full k-ary tree, the task is to construct the full k-ary tree and return its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children. Examples: Input: preorder[] = {1, 2, 5, 6, 7, 3, 8, 9, 10, 4}, k = 3 Output: Postorder traversal of constructed full k-ar
6 min read
Construct a special tree from given preorder traversal
Given an array pre[] that represents the Preorder traversal of a special binary tree where every node has either 0 or 2 children. One more array preLN[] is given which has only two possible values ‘L’ and ‘N’. The value ‘L’ in preLN[] indicates that the corresponding node in Binary Tree is a leaf node and the value ‘N’ indicates that the correspond
12 min read
Check if a given array can represent Preorder Traversal of Binary Search Tree
Given an array of numbers, the task is to check if the given array can represent the preorder traversal of a Binary Search Tree. Examples: Input: pre[] = {40, 30, 35, 80, 100}Output: trueExplanation: Given array can represent preorder traversal of below tree Input: pre[] = {2, 4, 1}Output: falseExplanation: Given array cannot represent preorder tra
11 min read
Find n-th node in Preorder traversal of a Binary Tree
Given a binary tree. The task is to find the n-th node of preorder traversal. Examples: Input: Output: 50Explanation: Preorder Traversal is: 10 20 40 50 30 and value of 4th node is 50.Input: Output : 3Explanation: Preorder Traversal is: 7 2 3 8 5 and value of 3rd node is 3. Table of Content [Naive Approach] Using Pre-Order traversal - O(n) Time and
11 min read
Modify a binary tree to get preorder traversal using right pointers only
Given a binary tree. The task is to modify it in such a way that after modification preorder traversal of it can get only with the right pointers. During modification, we can use right as well as left pointers. Examples: Input : Output : Explanation: The preorder traversal of given binary tree is 10 8 3 5 2. Table of Content [Expected Approach - 1]
12 min read
Print Postorder traversal from given Inorder and Preorder traversals
Given two arrays represent Inorder and Preorder traversals of a binary tree, the task is to find the Postorder traversal. Example: Input: in[] = [4, 2, 5, 1, 3, 6] pre[] = [1, 2, 4, 5, 3, 6]Output: 4 5 2 6 3 1Explanation: Traversals in the above example represents following tree: A naive method is to first construct the tree, then use a simple recu
11 min read
Preorder Traversal of Binary Tree
Preorder traversal is defined as a type of tree traversal that follows the Root-Left-Right policy where: The root node of the subtree is visited first.Then the left subtree is traversed.At last, the right subtree is traversed.Algorithm for Preorder Traversal of Binary TreeThe algorithm for preorder traversal is shown as follows: Preorder(root): If
7 min read
Morris traversal for Preorder
Given a Binary Tree, the task is to print its Preorder Traversal, without using recursion or stack. Examples: Input: Output: 1 2 4 5 3Explanation: Preorder traversal (Root->Left->Right) of the tree is 1 2 4 5 3 Input: Output: 8 1 7 10 5 10 6 6Explanation: Preorder traversal (Root->Left->Right) of the tree is 8 1 7 10 5 10 6 6 Approach:
9 min read
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
There are two common ways to traverse a graph, BFS and DFS. Considering a Tree (or Graph) of huge height and width, both BFS and DFS are not very efficient due to following reasons. DFS first traverses nodes going through one adjacent of root, then next adjacent. The problem with this approach is, if there is a node close to root, but not in first
10 min read
Iterative Postorder traversal | Set 3
We have seen different ways of performing postorder traversal on Binary Trees. Post Order Traversal.Iterative Postorder Traversal using Two Stacks.Iterative Postorder Traversal using One Stack. Here is another way of performing the postorder traversal on a Binary Tree iteratively using a single stack.Consider the Below Terminologies: 0 - Left eleme
7 min read
Iterative Depth First Traversal of Graph
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal (DFS) of a tree. The only catch here is, unlike trees, graphs may contain cycles, so a node might be visited twice. To avoid processing a node more than once, use a boolean visited array. Example: Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 ->
15+ min read
Iterative Postorder Traversal | Set 2 (Using One Stack)
We have discussed a simple iterative postorder traversal using two stacks in the previous post. In this post, an approach with only one stack is discussed. The idea is to move down to leftmost node using left pointer. While moving down, push root and root's right child to stack. Once we reach leftmost node, print it if it doesn't have a right child
15+ min read
Iterative diagonal traversal of binary tree
Given a Binary Tree, the task is to print the diagonal traversal of the binary tree.Note: If the diagonal element are present in two different subtrees, then left subtree diagonal element should be taken first and then right subtree. Example: Input: Output: 8 10 14 3 6 7 13 1 4Explanation: The above is the diagonal elements in a binary tree that be
13 min read
Iterative Postorder Traversal | Set 1 (Using Two Stacks)
Given a binary tree, the task is to find the postorder traversal of the tree without using recursion.Examples: Input: Output: 4 5 2 3 1Explanation: Postorder traversal (Left->Right->Root) of the tree is 4 5 2 3 1. Input: Output: 10 7 1 6 10 6 5 8 Explanation: Postorder traversal (Left->Right->Root) of the tree is 10 7 1 6 10 6 5 8 . App
10 min read
Level order traversal of Binary Tree using Morris Traversal
Given a binary tree, the task is to traverse the Binary Tree in level order fashion.Examples: Input: 1 / \ 2 3 Output: 1 2 3 Input: 5 / \ 2 3 \ 6 Output: 5 2 3 6 Approach: The idea is to use Morris Preorder Traversal to traverse the tree in level order traversal.Observations: There are mainly two observations for the traversal of the tree using Mor
11 min read
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 Post Order: 12 8 4 9 5 2 6 10 11 7 3 1 In Order: 8 12 4 2 9 5 1 6
9 min read
Modify Binary Tree by replacing each node with the sum of its Preorder Predecessor and Successor
Given a binary tree consisting of N nodes, the task is to replace each node in the binary tree with the sum of its preorder predecessor and preorder successor. Examples: Input: 2 / \ 3 4 / \ / \ 6 5 7 8 Output: 3 / \ 8 12 / \ / \ 8 10 12 7 Explanation: For Node 2: Preorder predecessor = 0 (as preorder predecessor is not present), preorder successor
13 min read
Number of Binary Trees for given Preorder Sequence length
Count the number of Binary Tree possible for a given Preorder Sequence length n.Examples: Input : n = 1 Output : 1 Input : n = 2 Output : 2 Input : n = 3 Output : 5 Background : In Preorder traversal, we process the root node first, then traverse the left child node and then right child node. For example preorder traversal of below tree is 1 2 4 5
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg