DSA Tutorial



IN ORDER TRAVERSAL


🌿 Inorder Traversal in DSA (Binary Tree)

Inorder traversal is a depth-first traversal method where we visit:

Inorder Order: Left β†’ Root β†’ Right
πŸ”½ Click to View Example Tree
          1
         / \
        2   3
       / \
      4   5

      ➀ Inorder Traversal Output: 4 2 5 1 3
      

🧠 Inorder Traversal Algorithm

  • Recursively traverse the left subtree.
  • Visit the root node.
  • Recursively traverse the right subtree.

πŸ’» Python Code

class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def inorder(root):
    if root:
        inorder(root.left)       # Left
        print(root.val, end=" ") # Root
        inorder(root.right)      # Right
  

βš™οΈ Output

➀ 4 2 5 1 3

🌐 Real-Time Use Case

πŸ“Œ For Binary Search Trees (BSTs): Inorder traversal gives the nodes in sorted order! It’s one of the most important uses of inorder.

πŸ”„ Iterative Inorder Traversal (Using Stack)

When recursion depth is a concern, we can use a stack to simulate inorder traversal:

def inorder_iterative(root):
    stack = []
    current = root
    while stack or current:
        while current:
            stack.append(current)
            current = current.left
        current = stack.pop()
        print(current.val, end=" ")
        current = current.right
  
βœ”οΈ Bonus: Inorder traversal is key to understanding how a tree is structured and used in BST validation problems.

πŸ“Œ Summary

  • Visits nodes in Left β†’ Root β†’ Right order.
  • Useful in Binary Search Trees for sorted output.
  • Can be implemented recursively or using a stack.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review