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.Binary Tree Inorder TraversalLeft -> Root -> Right: traverse left subtree, process current node, traverse right subtreeeasy
- 2.Validate Binary Search TreeInorder traversal with prev pointer: if curr.Val <= prev.Val -> return falsemedium
- 3.Kth Smallest Element in a BSTInorder traversal + count: return node value when count == K (early stop!)medium
- 4.Minimum Absolute Difference in BSTInorder traversal tracking prev pointer: minDiff = min(minDiff, curr.Val - prev.Val)easy
- 5.BST IteratorControlled Inorder DFS using stack: initially push all left nodes; pop & push right child left pathmedium
- 6.Recover Binary Search TreeInorder DFS detecting 1 or 2 swapped nodes where prev.Val > curr.Valmedium
- 7.Convert BST to Greater TreeReverse Inorder (Right -> Root -> Left) maintaining running summedium
- 8.Find Mode in Binary Search TreeInorder traversal tracking current count & max count without extra memoryeasy
- 9.Two Sum IV — Input is a BSTInorder to sorted array + Two Pointers, or HashSet during traversaleasy
- 10.Inorder Successor in BSTIf right subtree exists: min of right subtree. Else: last left-turn ancestormedium
- 11.Inorder Predecessor in BSTIf left subtree exists: max of left subtree. Else: last right-turn ancestormedium
- 12.Increasing Order Search TreeInorder DFS rewiring right pointers (node.Left = nil)easy
- 13.Binary Search Tree to Sorted ListInorder DFS connecting prev.Right = curr and curr.Left = prevmedium
- 14.Balance a Binary Search TreeInorder to sorted array + construct balanced BST from middlemedium
- 15.Convert BST to Sorted ArrayInorder DFS appending node values to sliceeasy
Also Important
8 more questions worth practicing.
- 16.Closest Binary Search Tree ValueBinary search or Inorder tracking min abs difference to targeteasy
- 17.Range Sum of BSTInorder DFS with pruning (skip Left if val < low, skip Right if val > high)easy
- 18.Trim a Binary Search TreeInorder DFS rewiring pointers for values outside [low, high] rangemedium
- 19.Binary Tree to Doubly Linked ListInorder DFS connecting prev & curr pointers into circular DLLmedium
- 20.Merge Two BSTsInorder both BSTs to sorted arrays + merge two sorted arrays + rebuild BSTmedium
- 21.Kth Largest Element in BSTReverse Inorder (Right -> Root -> Left) + count to Kmedium
- 22.Recover BST with Two Swapped NodesInorder traversal finding two out-of-order nodes and swapping valueshard
- 23.Construct BST VariantsInorder & Preorder combinationsmedium
How to Think
- Need sorted values from BST?Inorder Traversal (Left -> Root -> Right)
- Need Kth smallest?Inorder + Count to K (early stop)
- Need compare each BST value with previous?Inorder + prev pointer
- 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
}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
Inorder is strictly LEFT -> ROOT -> RIGHT. Processing the node before left children is Preorder!
Inorder is ONLY sorted for a Binary Search Tree (BST)! Standard binary trees have no ordering guarantee.
Do not store all N node values! Increment a counter during traversal and stop immediately when count == K to save space.
The loop condition MUST be curr != nil || len(stack) > 0. Using && will stop traversal prematurely!
Interview Rules
- 1. Sorted values from BST needed? → Inorder Traversal
- 2. Traversal sequence? →
LEFT -> ROOT -> RIGHT - 3. Kth smallest in BST? → Inorder + counter early stop
- 4. Compare adjacent BST values? → Track
prevpointer during traversal - 5. Recover BST? → Detect sorted order violations (
prev.Val > curr.Val) - 6. BST Iterator? → Explicit stack storing path to next smallest element
- 7. Inorder Successor? → Smallest node in right subtree (go Right once, then Left as far as possible)
- 8. Overall Complexity → Time:
O(N)| Stack Space:O(H)(O(log N)balanced,O(N)skewed)
Small Rules
- Rule 1: Inorder processes the root in between the left and right subtrees.
- Rule 2: Inorder traversal of a valid BST is strictly sorted in ascending order.
- Rule 3:Iterative inorder uses a stack: push left path, pop & process, move right.
- Rule 4: Track a prev pointer to compare adjacent values without an extra array.
- Rule 5: Early stop at count == K for Kth smallest to keep space O(H).
Production Thinking
Ordered Tree Data Exports → Exporting in-memory ordered index structures to sorted CSV/JSON
Expression Tree Infix Evaluation → Evaluating algebraic expressions in standard mathematical infix notation (2 + 3) * 4
Database B-Tree Ordered Scans → Performing range scans across ordered index pages in database engines
Inorder Successor / Iterator → Building 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."