For working professionals
For fresh graduates
More
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.
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.
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.
inorderTraversal(node):
if node is not null:
inorderTraversal(node.left)
visit(node)
inorderTraversal(node.right)
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.
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.
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.
Recursive inorder traversal is a very basic technique. All we have to do is take the following actions:
The iterative approach uses a stack to keep track of nodes, mimicking the recursive process. Here’s how it works:
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 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.
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:
The Inorder traversal of given binary tree is -
15 25 28 30 35 40 45 50 55 60 70
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:
The Inorder traversal of given binary tree is -
14 24 27 29 34 39 44 49 54 59 69
When working with trees, there are numerous benefits to employing inorder traversal.
You should be aware of a few drawbacks while utilizing inorder traversal.
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.
There are three main algorithms for binary tree traversal:
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.
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.
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.
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
Consider the binary tree:
1
/ \
2 3
/ \
4 5
The inorder traversal of this tree would be: 4, 2, 5, 1, 3.
Pavan Vadapalli
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.