×

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree, and all of them have their own functions as well as implementations. These operations are insertion, deletion, traversal and many more. In this article, we are briefly going to discuss the various different methods of traversal. The traversal operation has many of its own approaches that are inorder, postorder and preorder traversal.

Inorder traversal

When we have a binary tree, and we want to explore and traverse that tree in ascending order, then we usually use this kind of approach, which is the inorder traversal. When we talk about linear data structures, which are linked lists, arrays, stacks, and queues, in those data structures we can only explore or traverse in one direction. Still, in non-linear data structures, such as the tree and graphs, there are several different ways in which we can traverse or explore the data. Here, we will discuss another way of traversing the data structure, which is the inorder traversal.

The inorder traversal method generally hovers over the basic principle of left root right policy. In this policy, the left root right implies that the left subtree of the current root node is visited first; when we start traversing, we visit the root node, then we commute to the right subtree, and its root node is visited. Here, the name itself suggests that the traversal or exploration occurs between the left and right subtrees.

Mainly there are two given approaches or ways in which we can simply use for the traversal in the tree. They are: -

  1. Inorder traversal using recursion
  2. Inorder traversal using an iterative method

Now we will describe each of them in detail: -

Inorder traversal using recursion

In this type of inorder traversal, we first have to process and configure all the given nodes in the left subtree, and then we have to store and keep them intact in the root node. After that, when we have processed and configured all the nodes present in the right subtree.

Inorder traversal using an iterative method

The iterative traversal of the tree is done by using the stack data structure and is one of the best methods to traverse a tree. We first have to initialize the stack and then push the current node onto the stack.

Algorithm for ignored traversal

  1. In this, firstly, we have to visit all the nodes and vertices that are situated in the left subtree.
  2. Then we have to commute to the root node.
  3. After finishing that, we will visit all the nodes that are present in the right subtree.
inorder(root->left)
display(root->data)
inorder(root->right)

Implementation of inorder traversal using recursive method

#include <iostream>
using namespace std;
struct Node
{
    int data;
    Node *lft, *rt;
 
    Node(int info)
    {
        this->info = info;
        this->lft = this->rt = nullpointr;
    }
};
 
// We will use a recursive function to perform the mechanism of inorder traversal on the tree. 
void inorder(Nod* root)
{
    // return if found out the current node is clear and 
    if (root == nullpointr) {
        return;
    }
 
    // We have to travel to the left subtree 
    inorder(root->lft);
 
    //We will next showcase the information part of the root(or current node). 
    cout << root->info << " ";
 
    // We have to travel to the right subtree 
    inorder(root->rt);
}
 
int main()
{
    /* Build the following tree
               1
             /   \
            /     \
           2       3
          /      /   \
         /      /     \
        4      5       6
              / \
             /   \
            7     8
    */
 
    Nod* root = new Nod(1);
    root->lft = new Nod(2);
    root->rt = new Nod(3);
    root->lft->lft = new Nod(4);
    root->rt->lft = new Nod(5);
    root->rt->rt = new Nod(6);
    root->rt->lft->lft = new Nod(7);
    root->rt->lft->rt = new Nod(8);
 
    inorder(root);
 
    return 0;
}

Output:

BINARY TREE INORDER TRAVERSAL

Implementation of inorder traversal using the iterative method

#include <iostream>
#include <stack>
using namespace std;
 struct Node
{
    int info;
    Nod *lft, *rt;
 
    Nod(int info)
    {
        this->info = info;
        this->lft = this->rt = nullpointr;
    }
};
 
// We will use an Iterative function to perform the mechanism of inorder traversal on the tree. 
 void inorderIterative(Nod* root)
{
    // We will first have to create a vacant stack which is completely empty
    stack<Nod*> stack;
 
    // We have to begin from the root node and then initialize the current node to the root node 
    Nod* current = root;
 
    // By any chance, if the current node which is provided to us is zero and the stack is also vacant, then we are done
    while (!stack.empty() || current!= nullpointr)
    {
        // when we find the current node, occupy it and press it back into the given stack and then shift it to the left node.
        if (current!= nullpointr)
        {
            stack.push(current);
            current = current->lft;
        }
        else {
            // In case the current node that we have is empty; then we have to pop an element from the allotted stack. 
            // Set it to print the result
            current = stack.top();
            stack.pop();
            cout << current->info << " ";
 
            curr = current->rt;
        }
    }
}
 
int main()
{
    /* Build the following tree
               1
             /   \
            /     \
           2       3
          /      /   \
         /      /     \
        4      5       6
              / \
             /   \
            7     8
    */
 
    Nod* root = new Nod(1);
    root->lft = new Nod(2);
    root->rt = new Nod(3);
    root->lft->lft = new Nod(4);
    root->rt->lft = new Nod(5);
    root->rt->rt = new Nod(6);
    root->rt->lt->lt = new Nod(7);
    root->rt->lft->rt = new Nod(8);
 
    inorderIterative(root);
 
    return 0;
}

Output:

BINARY TREE INORDER TRAVERSAL

Related Topics

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Comb Sort

Brush sort is a fairly direct orchestrating computation at first arranged by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered (and given the name "Combsort") by Stephen Lacey and...

5 minutes read.

What is the difference between DFS and BFS?

What is BFS? BFS is generally known as the low level traversal. As we already know that it stands for breadth first search and is mainly used in the queue data...

4 minutes read.

Sorting Algorithms in Data Structures

A sorting algorithm is used to organize the elements of an array or list. Sorting an array, for example. Unsorted array 572941 Sorted array 124579 We're sorting the array in ascending order right now. This procedure...

4 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.

Primitive Data Structure in C

The data structure is a logical or mathematical model for organizing and structuring the main memory or elements. We can classify the data structures in two ways one is primitive, and...

10 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

Convert Sorted List to Binary Search Tree

Implementation // creating the C++ implementation of the following approach: - #include <bits/stdc++.h> using namespace std; /* Create the link list node and see its implementation. */ class L__Nod { public: int record; L__Nod* next; }; /* constructing a new binary...

15 minutes read.

Understanding Data Processing

Introduction Data In our everyday lives, any task that we perform online is related to data. Millions of pieces of data are produced every second across the globe. Data production is largely...

4 minutes read.

Assembly Line Scheduling

If we take an example of a car factory, there are two assembly lines. In an assembly line, we can assemble and repair the parts of a car. Now, suppose...

5 minutes read.

What is a Sparse Matrix in Data Structure?

Definition A matrix in which a few non-zero elements are present is called a Sparse matrix. In a Sparse matrix, almost all the matrices are filled with zero (0). A matrix...

5 minutes read.

Burning binary tree

Burn the Binary tree starting from the target node You have given a binary tree and a target node value. Now you have to burn the tree from target node. You...

4 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Find Number of Minimum Insertion to Make a String Palindrome

You have been given a string. You have to find out the number of minimum insertions to make this string palindrome. The string will contain only lower case alphabets. Note:What is...

4 minutes read.

Object-Oriented Analysis and Design

While designing a system, one should know all the requirements or needs of the plan beforehand, and to do so, we should use a systematic approach to analyze the goal...

3 minutes read.

Data Structure Prefix to Postfix Conversion

Prefix to Postfix Conversion Prefix: As the name suggests if the operator placed before the operands called the prefix expression.  The form of prefix expression is (operator, operand1, operand2). Example:  *+EF-GH (Infix:...

2 minutes read.

Advantages and Disadvantages of Linked List

Advantages of Linked List The linked list is a dynamic data structure.You can also decrease and increase the linked list at run-time. That is, you can allocate and deallocate memory at...

3 minutes read.

Tree vs Graph: Data Structure

Difference Between Tree and Graph What is Tree? A tree is a non-linear data structure and finite collection of elements called node. A tree, in which the data items are arranged in...

3 minutes read.