#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Trees

In-order Traversal of Binary Search Tree

In-order traversal is one of the fundamental tree traversal techniques. For a Binary Search Tree (BST), in-order traversal visits nodes in non-decreasing (ascending) order of their values. This makes it particularly useful for retrieving sorted data from a BST.

Traversal Order

In-order traversal follows the pattern: Left → Root → Right. For every node, you first visit its left subtree, then the node itself, and finally its right subtree.

Recursive Implementation

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

def inorder_recursive(root, result=None):
    if result is None:
        result = []
    if root:
        inorder_recursive(root.left, result)
        result.append(root.val)
        inorder_recursive(root.right, result)
    return result

# Example usage
root = Node(5)
root.left = Node(3)
root.right = Node(8)
root.left.left = Node(2)
root.left.right = Node(4)

print(inorder_recursive(root))  # Output: [2, 3, 4, 5, 8]

Iterative Implementation (Using Stack)

def inorder_iterative(root):
    result = []
    stack = []
    current = root
    while stack or current:
        while current:
            stack.append(current)
            current = current.left
        current = stack.pop()
        result.append(current.val)
        current = current.right
    return result

# Output: [2, 3, 4, 5, 8]

Complexity

AspectComplexity
TimeO(n) — visits every node exactly once
Space (recursive)O(h) — recursion stack, h = height of tree
Space (iterative)O(h) — explicit stack, worst-case O(n) for skewed tree

Key Properties

  • For a BST, in-order traversal produces a sorted list of all values.
  • It is often used to validate whether a binary tree is a BST (check if the traversal output is sorted).
  • It is a depth-first traversal (DFS) technique.

Applications

  • Extracting sorted data from a BST without additional sorting cost.
  • Validating BST properties (checking if in-order output is strictly increasing).
  • Finding the k-th smallest element in a BST (by stopping early during traversal).
  • Tree serialization and deserialization.

Following the Stack Step by Step

The iterative version is easier to trust once you watch the stack change. Using the example tree with root 5, left child 3 (children 2 and 4) and right child 8:

ActionStack (bottom to top)Output so far
Push 5, 3, 2 while going left5, 3, 2empty
Pop 2, it has no right child5, 32
Pop 3, move to right child 4 and push it5, 42, 3
Pop 452, 3, 4
Pop 5, move to right child 8 and push it82, 3, 4, 5
Pop 8, stack and current are emptyempty2, 3, 4, 5, 8

The stack always holds the chain of ancestors whose left side is still being processed. That is why its size never exceeds the tree height.

Morris Traversal: In-order With No Extra Memory

Both versions above need O(h) extra space. Morris traversal brings this down to O(1) by temporarily linking each node's in-order predecessor back to it, then removing the link after use.

def inorder_morris(root):
    result = []
    current = root
    while current:
        if current.left is None:
            result.append(current.val)
            current = current.right
        else:
            pred = current.left
            while pred.right and pred.right is not current:
                pred = pred.right
            if pred.right is None:
                pred.right = current      # create temporary thread
                current = current.left
            else:
                pred.right = None         # remove thread, restore tree
                result.append(current.val)
                current = current.right
    return result

Time stays O(n), because each edge is walked a bounded number of times. The trade-off is that the tree is modified during traversal, so it is unsafe if other threads read the tree at the same time.

Validating a BST and Finding the k-th Smallest

Instead of storing the whole traversal and checking it afterwards, track only the previous value. The moment a value is not larger than the previous one, the tree is not a valid BST.

def is_valid_bst(root):
    prev = None
    stack, current = [], root
    while stack or current:
        while current:
            stack.append(current)
            current = current.left
        current = stack.pop()
        if prev is not None and current.val <= prev:
            return False
        prev = current.val
        current = current.right
    return True

For the k-th smallest element, use the same loop with a counter and return as soon as the counter reaches k. On a balanced tree with a small k, this touches only a small part of the tree.

Where Beginners Slip

  • Checking only parent and child. A tree where every node is larger than its left child can still be invalid, because a deep node may break the rule against a grandparent. In-order checking catches this; local comparisons do not.
  • Using a mutable default argument. Writing result=[] directly in the function signature shares one list across calls in Python. The None check in the recursive version avoids that.
  • Deep recursion on skewed trees. A tree built from already sorted input can be as tall as it is large, which may exceed Python's recursion limit. Prefer the iterative form for unknown input.
  • Mixing up traversal orders. Pre-order (Root, Left, Right) suits copying a tree; post-order (Left, Right, Root) suits deleting one; in-order is the one that yields sorted output.