Pattern #42

Inorder Traversal

Important interview questions, thinking patterns, Left-Root-Right processing, BST + Inorder = Sorted rule, prev pointer tracking, and Go code templates.

Must Solve

15 core questions — solve these first.

  1. 1.Binary Tree Inorder Traversal
    easy
  2. 2.Validate Binary Search Tree
    medium
  3. 3.Kth Smallest Element in a BST
    medium
  4. 4.Minimum Absolute Difference in BST
    easy
  5. 5.BST Iterator
    medium
  6. 6.Recover Binary Search Tree
    medium
  7. 7.Convert BST to Greater Tree
    medium
  8. 8.Find Mode in Binary Search Tree
    easy
  9. 9.Two Sum IV — Input is a BST
    easy
  10. 10.Inorder Successor in BST
    medium
  11. 11.Inorder Predecessor in BST
    medium
  12. 12.Increasing Order Search Tree
    easy
  13. 13.Binary Search Tree to Sorted List
    medium
  14. 14.Balance a Binary Search Tree
    medium
  15. 15.Convert BST to Sorted Array
    easy

Also Important

8 more questions worth practicing.

  1. 16.Closest Binary Search Tree Value
    easy
  2. 17.Range Sum of BST
    easy
  3. 18.Trim a Binary Search Tree
    medium
  4. 19.Binary Tree to Doubly Linked List
    medium
  5. 20.Merge Two BSTs
    medium
  6. 21.Kth Largest Element in BST
    medium
  7. 22.Recover BST with Two Swapped Nodes
    hard
  8. 23.Construct BST Variants
    medium

How to Think

  1. Need sorted values from BST?Inorder Traversal (Left -> Root -> Right)
  2. Need Kth smallest?Inorder + Count to K (early stop)
  3. Need compare each BST value with previous?Inorder + prev pointer
  4. Need next smallest repeatedly?Controlled Inorder + Stack (BST Iterator)

Go Inorder Code Templates

Recursive & Iterative Inorder in Go

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

// 1. Recursive Inorder: Left -> Root -> Right
func inorderRecursive(root *TreeNode) []int {
    result := []int{}
    var dfs func(node *TreeNode)
    dfs = func(node *TreeNode) {
        if node == nil {
            return
        }
        dfs(node.Left)
        result = append(result, node.Val) // Process Root in Middle!
        dfs(node.Right)
    }
    dfs(root)
    return result
}

// 2. Iterative Inorder Template: Push Left Path -> Pop & Process -> Move Right
func inorderIterative(root *TreeNode) []int {
    result := []int{}
    stack := []*TreeNode{}
    curr := root

    for curr != nil || len(stack) > 0 {
        // Go Left as far as possible
        for curr != nil {
            stack = append(stack, curr)
            curr = curr.Left
        }

        // Pop & Process
        curr = stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        result = append(result, curr.Val)

        // Move Right
        curr = curr.Right
    }
    return result
}

👉 Total Time: O(N) | Space: O(H) stack

The Golden Rule: BST + Inorder = Sorted Array

Because a Binary Search Tree guarantees Left < Node < Right, traversing it Inorder (Left -> Root -> Right) produces a strictly ascending sorted sequence!

// Validate BST using prev Pointer
func isValidBST(root *TreeNode) bool {
    var prev *TreeNode

    var inorder func(node *TreeNode) bool
    inorder = func(node *TreeNode) bool {
        if node == nil {
            return true
        }

        if !inorder(node.Left) {
            return false
        }

        // Check if sorted order is broken!
        if prev != nil && node.Val <= prev.Val {
            return false
        }
        prev = node

        return inorder(node.Right)
    }

    return inorder(root)
}

👉 Time: O(N) | Space: O(H) recursion stack

Iterative Inorder Loop Template

The canonical iterative tree traversal template uses an explicit stack:

// Standard Iterative Loop
for curr != nil || len(stack) > 0 {
    for curr != nil {
        stack = append(stack, curr)
        curr = curr.Left
    }
    curr = stack[len(stack)-1]
    stack = stack[:len(stack)-1]

    // process curr...

    curr = curr.Right
}
Visual Memory Rule
Inorder         → LEFT -> ROOT -> RIGHT (Root processed in middle)
BST + INORDER   → Strictly Sorted Array
Kth Smallest    → Count during Inorder & stop early at K
Validate BST    → Compare curr.Val against prev.Val
Iterative Loop  → Push left path -> Pop & process -> Move right

💡 Golden Rule: "Go left as far as possible, process the current node, then move right."

Common Interview Mistakes

1. Confusing Traversal Order

Inorder is strictly LEFT -> ROOT -> RIGHT. Processing the node before left children is Preorder!

2. Assuming Inorder is Sorted for General Trees

Inorder is ONLY sorted for a Binary Search Tree (BST)! Standard binary trees have no ordering guarantee.

3. Building Full Array for Kth Smallest

Do not store all N node values! Increment a counter during traversal and stop immediately when count == K to save space.

4. Wrong Iterative Loop Condition

The loop condition MUST be curr != nil || len(stack) > 0. Using && will stop traversal prematurely!

Interview Rules

  1. 1. Sorted values from BST needed? → Inorder Traversal
  2. 2. Traversal sequence?LEFT -> ROOT -> RIGHT
  3. 3. Kth smallest in BST? → Inorder + counter early stop
  4. 4. Compare adjacent BST values? → Track prev pointer during traversal
  5. 5. Recover BST? → Detect sorted order violations (prev.Val > curr.Val)
  6. 6. BST Iterator? → Explicit stack storing path to next smallest element
  7. 7. Inorder Successor? → Smallest node in right subtree (go Right once, then Left as far as possible)
  8. 8. Overall Complexity → Time: O(N) | Stack Space: O(H) (O(log N) balanced, O(N) skewed)

Small Rules

  1. Rule 1: Inorder processes the root in between the left and right subtrees.
  2. Rule 2: Inorder traversal of a valid BST is strictly sorted in ascending order.
  3. Rule 3:Iterative inorder uses a stack: push left path, pop & process, move right.
  4. Rule 4: Track a prev pointer to compare adjacent values without an extra array.
  5. Rule 5: Early stop at count == K for Kth smallest to keep space O(H).

Production Thinking

Ordered Tree Data ExportsExporting in-memory ordered index structures to sorted CSV/JSON

Expression Tree Infix EvaluationEvaluating algebraic expressions in standard mathematical infix notation (2 + 3) * 4

Database B-Tree Ordered ScansPerforming range scans across ordered index pages in database engines

Inorder Successor / IteratorBuilding next() iterators for large sorted collections without full array copies

Remember This

Inorder         → LEFT -> ROOT -> RIGHT
BST + Inorder   → SORTED
Kth Smallest    → Count inorder
Validate BST    → prev < current
Min Difference  → Compare neighbors
Recover BST     → Find broken order
Iterative Loop  → Go Left, Pop, Process, Right
Time            → O(N)

💡 Golden Rule: "Go left as far as possible, process the current node, then move right."