1. Home
Data Structure

Data Structure Tutorial: Everything You Need to Know

Learn all about data structures with our comprehensive tutorial. Master the fundamentals and advance your skills in organizing and managing data efficiently.

  • 60
  • 14
right-top-arrow

Tutorial Playlist

58 Lessons
18

Exploring Inorder Traversal: Navigating Binary Trees for Beginners

Updated on 02/08/2024434 Views

Introduction

The process of going through each node in a tree data structure in a particular order is called tree traversal. A tree can be traversed in three main ways: inorder, preorder, and postorder. This article will concentrate on inorder traversal, which goes through the subtrees on the left, the root node, and the right in that order.

Overview

In this article, we will talk about the inorder traversal in data structures.

The inorder traversal is used to navigate the nodes in ascending order. The steps needed for the inorder traversal are as follows:

—-Visit all nodes in the left subtree, then the root, and finally all nodes in the right subtree.

A linear data structure has only one way to traverse the data, which is through stack, array, queue, etc. However, there are several ways to go around the data in hierarchical data structures, such as trees. We will now talk about in-order traversal, which is an alternative method of navigating the tree data structure.

What is Binary Tree order traversal?

The idea of inorder traversal may be a little unclear if you're not very familiar with tree data structures. To put it simply, in-order traversal is the process of going through a tree's nodes in a particular order. Preorder traversal, which visits the root node first, the left subtree, and then the right subtree, is the most popular method of tree traversal. Postorder traversal, on the other hand, goes to the root node after visiting the left subtree and the right subtree.

Between these two extremes lies in order traversal. An inorder traversal of a tree goes to the root node, left subtree, and the right subtree in that order. Although this arrangement may appear random at first, it actually serves a very practical purpose.

Printing every value in a tree in sorted order is a typical use case for inorder traversal. This is due to the fact that if a tree is a binary search tree (BST), visiting its nodes in a left-to-right order will result in accessing them in a sorted order.

Inorder Traversal Algorithm:

inorderTraversal(node):

    if node is not null:

        inorderTraversal(node.left)

        visit(node)

        inorderTraversal(node.right)

The Inordeer Traversal Applications

Binary search tree construction is one of the most popular uses for inorder traversal. We can build the tree such that the leftmost element is always greater than the current node and the rightmost element is always less than the current node by going through it in order.

Finding a binary search tree's kth smallest element can also be accomplished by inorder traversal. We can stop when we reach the kth element and return its value by keeping track of the number of items visited during the traversal.

A balanced binary search tree can also be built from a sorted array using in-order traversal. To do this, the array is divided recursively into two parts, each of which is traversed in order, and the two parts are then combined into a single balanced tree.

How Inorder Traversal Works

One of the most widely used methods for navigating a tree data structure is inorder traversal. One kind of depth-first search is this one. Visiting the left child, the root node, and then the right child is the concept behind in-order traversal. Although it isn't always followed, this sequence helps you to recall how inorder traversal operates.

Numerous issues can be resolved with in-order traversal, including locating the kth element in a tree and publishing every element in a tree in the desired order.

Recursion or an iterative method can be used to implement in-order traversal. Although the iterative approach is more efficient, the recursive approach is simpler to comprehend and code.

  • The Inorder Traversal Iterative Approach

Although it is a little more complicated, the iterative method of in-order traversal is more effective. Stack data is the idea underlying the iterative technique.

  • The Inorder Recursive Approach

Recursive inorder traversal is a very basic technique. All we have to do is take the following actions:

  • Visit the left child of the root node.
  • Visit the root node.
  • Visit the right child of the root node.

Iterative Inorder Traversal Using a Stack

The iterative approach uses a stack to keep track of nodes, mimicking the recursive process. Here’s how it works:

  1. Initialize an empty stack.
  2. Start from the root node and push all the left nodes onto the stack until you reach the leftmost node.
  3. Pop a node from the stack, visit and push its right subtree onto the stack.
  4. Do the steps 2 and again until the stack is empty.

Python Example:

class TreeNode:

    def __init__(self, value=0, left=None, right=None):

        self.value = value

        self.left = left

        self.right = right

def inorderTraversal(root):

    stack = []

    result = []

    current = root

while stack or current:

        while current:

            stack.append(current)

            current = current.left

        current = stack.pop()

        result.append(current.value)

        current = current.right

return result

# Example Usage

root = TreeNode(1, None, TreeNode(2, TreeNode(3)))

print(inorderTraversal(root))  # Output: [1, 3, 2]

Java Example:

import java.util.ArrayList;

import java.util.List;

import java.util.Stack;

class TreeNode {

    int value;

    TreeNode left;

    TreeNode right;

    TreeNode(int value) {

        this.value = value;

        left = right = null;

    }

}

public class BinaryTree {

    public List<Integer> inorderTraversal(TreeNode root) {

        List<Integer> result = new ArrayList<>();

        Stack<TreeNode> stack = new Stack<>();

        TreeNode current = root;

while (current != null || !stack.isEmpty()) {

            while (current != null) {

                stack.push(current);

                current = current.left;

            }

            current = stack.pop();

            result.add(current.value);

            current = current.right;

        }

return result;

    }

// Example Usage

    public static void main(String[] args) {

        BinaryTree tree = new BinaryTree();

        TreeNode root = new TreeNode(1);

        root.right = new TreeNode(2);

        root.right.left = new TreeNode(3);

System.out.println(tree.inorderTraversal(root));  // Output: [1, 3, 2]

    }

}

Inorder Traversal Complexity

Inorder traversal has an O(n) time complexity, where 'n' is the binary tree's size.

However, if the stack size for function calls is ignored, the space complexity of an inorder traversal is O(1). If not, the inorder traversal's space complexity is O(h), where 'h' is the tree's height.

Example of how to implement Inorder Traversal

Let's now examine how inorder traversal is implemented in several computer languages.

Program: Create a C program that uses the in-order traversal technique.

#include <stdio.h>  

#include <stdlib.h>  

struct node {  

    int element;  

    struct node* left;  

    struct node* right;  

};  

/*To create a new node*/  

struct node* createNode(int val)  

{  

    struct node* Node = (struct node*)malloc(sizeof(struct node));  

    Node->element = val;  

    Node->left = NULL;  

    Node->right = NULL;  

    return (Node);  

}  

/*function to traverse the nodes of binary tree in Inorder*/  

void traverseInorder(struct node* root)  

{  

    if (root == NULL)  

        return;  

    traverseInorder(root->left);  

    printf(" %d ", root->element);  

    traverseInorder(root->right);  

}  

int main()  

{  

    struct node* root = createNode(40);  

    root->left = createNode(30);  

    root->right = createNode(50);  

    root->left->left = createNode(25);  

    root->left->right = createNode(35);  

    root->left->left->left = createNode(15);  

    root->left->left->right = createNode(28);  

    root->right->left = createNode(45);  

    root->right->right = createNode(60);  

    root->right->right->left = createNode(55);  

    root->right->right->right = createNode(70);      

    printf("\n The Inorder traversal of given binary tree is -\n");  

    traverseInorder(root);  

    return 0;  

}

 Output:

Here is a C++ code illustrating the same:

#include <iostream>  

using namespace std;  

struct node {  

    int element;  

    struct node* left;  

    struct node* right;  

};  

/*To create a new node*/  

struct node* createNode(int val)  

{  

    struct node* Node = (struct node*)malloc(sizeof(struct node));  

    Node->element = val;  

    Node->left = NULL;  

    Node->right = NULL;  

    return (Node);  

}  

/*function to traverse the nodes of binary tree in Inorder*/  

void traverseInorder(struct node* root)  

{  

    if (root == NULL)  

        return;  

    traverseInorder(root->left);  

    cout<<" "<<root->element<<" ";  

    traverseInorder(root->right);  

}  

int main()  

{  

    struct node* root = createNode(39);  

    root->left = createNode(29);  

    root->right = createNode(49);  

    root->left->left = createNode(24);  

    root->left->right = createNode(34);  

    root->left->left->left = createNode(14);  

    root->left->left->right = createNode(27);  

    root->right->left = createNode(44);  

    root->right->right = createNode(59);  

    root->right->right->left = createNode(54);  

    root->right->right->right = createNode(69);      

    cout<<"\n The Inorder traversal of given binary tree is -\n";  

    traverseInorder(root);  

    return 0;  

Output:

Inorder Traversal Advantages

When working with trees, there are numerous benefits to employing inorder traversal.

  • The ease with which data can be retrieved is one of its main benefits. This is due to the fact that the leftmost child is always visited first in an inorder traverse. Consequently, all of the data is saved in an easily retrievable arrangement.
  • The ability to quickly determine whether or not a tree is balanced is another benefit of the inorder traverse. This is because the leftmost child is always visited first by the inorder traversal algorithm. The method will therefore always visit the same number of nodes on either side of the tree if the tree is balanced.

Inorder Traversal Disadvantages

You should be aware of a few drawbacks while utilizing inorder traversal.

  • First of all, if you're not familiar with recursion, it could be challenging to implement.
  • Second, it's not the fastest algorithm available; preorder and postorder traversal are two examples of faster algorithms that can traverse a tree.
  • Ultimately, not all tree types lend themselves well to an inorder traversal; in certain cases, a different technique, such as breadth-first search, would work better with the particular data structures at hand.

Conclusion

In computer science, inorder traversal is a fundamental algorithm used to traverse binary trees. It systematically visits all nodes in a specific order, providing a way to access data elements stored in the tree. Understanding inorder traversal is essential for grasping the fundamentals of tree data structures and algorithms.

Understanding inorder traversal is crucial for mastering tree algorithms and effectively resolving a variety of computational issues, whether they are handled recursively or iteratively. Beginners can explore the rich geography of binary trees and realize their potential in software development and other fields by understanding the concepts presented in this tutorial.

Frequently Asked Questions:

  1. What are the algorithms of binary tree traversal?

There are three main algorithms for binary tree traversal:

  • Inorder Traversal: Visit the left subtree, current node, and right subtree.
  • Preorder Traversal: Visit the current node, left subtree, and right subtree.
  • Postorder Traversal: Visit the left subtree, right subtree, and current node.
  1. What is the order of traversal of a binary tree?

The order of traversal of a binary tree depends on the traversal algorithm used. In order traversal, nodes are visited in non-decreasing order based on their values.

  1. What is the in-order traversal algorithm?

The inorder traversal algorithm involves visiting nodes in the order: left subtree, current node, right subtree. It is commonly used for binary search trees to retrieve elements in sorted order.

  1. What is the algorithm of level order traversal?

The level order traversal algorithm visits nodes level by level, starting from the root and moving to subsequent levels from left to right. It utilizes a queue data system to keep track of nodes at each level.

  1.  What is a binary tree with an example?

A binary tree is a hierarchical data structure having nodes, where each node has at most two children: a left child and a right child. Here's an example of a binary tree:

     1

    / \

   2   3

  / \

 4   5

  1. What is an example of an inorder traversal?

Consider the binary tree:

     1

    / \

   2   3

  / \

 4   5

The inorder traversal of this tree would be: 4, 2, 5, 1, 3.

Pavan Vadapalli

Pavan Vadapalli

Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and l…Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...