# What Is Traversal in Data Structure With Example?

//

Larry Thompson

Traversal is an essential operation in data structures that allows us to visit each element in a data structure. It is particularly important when dealing with linear data structures such as arrays, linked lists, and stacks. Traversal helps to access, process, or manipulate the elements present in the data structure.

## Types of Traversal:

There are two common types of traversals – Sequential Traversal and Random Access Traversal. Let’s explore each of them with examples:

### 1. Sequential Traversal:

Sequential traversal involves accessing elements in a particular order, one after the other. This type of traversal is commonly used in linked lists and arrays.

Example 1:
Consider an array of integers: [4, 8, 2, 6]. To sequentially traverse this array using a loop in C++, you can use the following code snippet:

``````
int arr[] = {4, 8, 2, 6};
int size = sizeof(arr) / sizeof(arr);

for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
``````

The output of this code will be: 4 8 2 6, which represents the sequential traversal of the array.

### 2. Random Access Traversal:

Random access traversal allows accessing elements directly without going through each element one by one. This type of traversal is commonly used in data structures such as binary trees and matrices.

Example 2:
Consider a binary tree with the following structure:

``````
A
/ \
B   C
/ \   \
D   E   F
``````

To perform random access traversal on this binary tree, you can use depth-first traversal algorithms like pre-order, in-order, and post-order. Let's take the pre-order traversal as an example:

``````
void preOrderTraversal(Node* root) {
if (root != nullptr) {
cout << root->data << " "; // Print current node
preOrderTraversal(root->left); // Traverse left subtree
preOrderTraversal(root->right); // Traverse right subtree
}
}

// Example usage
Node* root = createBinaryTree(); // Assume this function creates the binary tree shown above
preOrderTraversal(root);
``````

The output of this code will be: A B D E C F, which represents the random access traversal of the binary tree.

## Conclusion:

In data structures, traversal plays a vital role in accessing and processing elements. Sequential traversal is useful for linear data structures, while random access traversal is important for hierarchical or non-linear structures. By understanding and implementing different types of traversals, you can efficiently work with various data structures in your programs.

• Sequential Traversal: Accesses elements one after another in a specific order.
• Random Access Traversal: Allows direct access to elements without sequential scanning.

Remember to choose the appropriate type of traversal depending on the data structure and your requirements. With these concepts in mind, you can now confidently traverse different data structures in your programs.