DSA In-order Traversal

DSA Tutorial

 DSA In-order Traversal – Complete Beginner Guide

(Concept • Steps • Example • Code • Complexity)

In-order Traversal is one of the Depth-First Search (DFS) traversal techniques for Binary Trees.
It is extremely important because in a Binary Search Tree (BST) it gives elements in sorted order.


1️⃣ What is In-order Traversal?

In In-order Traversal, nodes are visited in this order:

Left → Root → Right

 The root node is visited between the left and right subtrees.


2️⃣ Easy Way to Remember

IN = Root is IN the middle

So:

LeftRootRight

3️⃣ In-order Traversal – Step by Step

Example Binary Tree



Traversal Steps

  1. Go to leftmost node → 4

  2. Visit parent → 2

  3. Visit right child → 5

  4. Visit root → 1

  5. Visit right subtree → 3

 Output

4 2 5 1 3

4️⃣ In-order Traversal Algorithm

  1. Traverse the left subtree

  2. Visit the root node

  3. Traverse the right subtree


5️⃣ Pseudocode

Inorder(node):
if node == NULL:
return
Inorder(node.left)
print(node.data)
Inorder(node.right)

6️⃣ In-order Traversal – Recursive Code (C++)


 


7️⃣ Complete Example Program (C++)


 

Output

4 2 5 1 3

8️⃣ Iterative In-order Traversal (Using Stack)


 


9️⃣ Time & Space Complexity

 Time Complexity

O(n)

 Space Complexity

  • Recursive: O(h)

  • Iterative: O(h)
    (h = height of tree)


🔟 Special Importance in BST

 For a Binary Search Tree:

In-order Traversal → Sorted Output

Example BST

In-order Output:

5 10 15

1️⃣1️⃣ In-order vs Pre-order vs Post-order

Traversal Order
In-order Left → Root → Right
Pre-order Root → Left → Right
Post-order Left → Right → Root

 Interview Questions (In-order)

Q1. Why is in-order traversal important?
👉 Gives sorted data in BST

Q2. Can in-order traversal be done without recursion?
👉 Yes, using a stack

Q3. Time complexity?
👉 O(n)


Final Summary

✔ In-order traversal visits root in the middle
✔ Order: Left → Root → Right
✔ Crucial for BST sorting
✔ Implemented recursively or iteratively
✔ Time complexity: O(n)

You may also like...