3.4.5Trees

BST — inorder gives sorted order

1,911 words9 min readdifficulty · medium

WHAT is a BST? (precise foundation)

The key word in "BST" is Search — the ordering invariant exists precisely so we can binary-search through it.


WHY inorder produces sorted output

Derivation from scratch (proof by structural induction)

We never just assert it — we build the proof from the base case up.

Base case. An empty tree (or a single node) produces a list of length 1\le 1. A list of length 0 or 1 is trivially sorted. ✔

Inductive hypothesis (IH). Assume for any BST smaller than TT (i.e. its subtrees), inorder gives a sorted list.

Inductive step. Let TT have root rr, left subtree TLT_L, right subtree TRT_R.

  1. By IH, inorder(TL)\text{inorder}(T_L) is sorted, and by the BST property every key in TLT_L is <r< r. So: inorder(TL) is sorted, and its last element<r.\text{inorder}(T_L) \text{ is sorted, and its last element} < r.
  2. By IH, inorder(TR)\text{inorder}(T_R) is sorted, and every key in TRT_R is >r> r. So: inorder(TR) is sorted, and its first element>r.\text{inorder}(T_R) \text{ is sorted, and its first element} > r.
  3. Concatenate: [ ...sorted, all < r ] + [r] + [ all > r, sorted... ]. The boundary between left list and rr is increasing (last <r< r). The boundary between rr and right list is increasing (r<r < first). Why this matters: a concatenation of two sorted lists is itself sorted iff the last of the first \le first of the second — and we just proved both joins respect that. ✔

By induction, inorder of any BST is sorted. \blacksquare

Figure — BST — inorder gives sorted order

HOW to do it (code, two ways)

Worked trace

Tree:

        8
       / \
      3    10
     / \     \
    1   6     14
  • Dive left from 8 → 3 → 1. Print 1. 1 has no right.
  • Pop 3, print 3. Go right to 6, dive left (none), print 6.
  • Pop 8, print 8. Go right to 10, dive left (none), print 10, go right to 14, print 14.
  • Output: 1, 3, 6, 8, 10, 14 — sorted! Why? Each node printed only after its entire smaller-left family.

Complexity. Every node pushed/popped once → O(n)O(n) time. Space O(h)O(h) for the stack, where hh is height (O(logn)O(\log n) if balanced, O(n)O(n) worst-case skewed).


The reverse fact (Forecast-then-Verify)

Recall Verify

Yes — sorted inorder     \iff BST (with distinct keys). This gives a clean validation algorithm: do inorder, check each element >> previous. If any violation, it's not a BST. Cleaner than checking min/max ranges at every node.


Common mistakes (Steel-manned)


Flashcards

What property must every node satisfy in a BST?
All keys in its left subtree are smaller, all keys in its right subtree are larger (recursively).
What traversal order is "inorder"?
Left, then Node, then Right (L, N, R).
Why does inorder of a BST give sorted output?
Because left subtree (all smaller) is printed before the node, and right subtree (all larger) after — recursively true at every node.
What is the recursive equation for inorder of tree T?
inorder(T) = inorder(left) + [root] + inorder(right).
What is the base case of the inorder-sorted proof?
An empty tree or single node, which is trivially sorted (length ≤ 1).
Time and space complexity of inorder traversal?
O(n) time; O(h) space (h = height) for the stack/recursion.
How do you validate a BST using inorder?
Run inorder and check each element is strictly greater than the previous.
Why is checking only immediate children insufficient for BST validation?
A node deep in a subtree can violate an ancestor's bound even if every parent–child pair looks fine.
Is the converse true: sorted inorder implies BST?
Yes, for distinct keys — sorted inorder ⇔ BST.
What does the explicit stack in iterative inorder remember?
The postponed "visit node + go right" work for ancestors while we dive down the left spine.

Recall Feynman: explain to a 12-year-old

Imagine kids lined up in a family tree where every kid is taller than everyone on their left and shorter than everyone on their right. You want to call them out shortest-to-tallest. So at each kid you say: "wait, let me first call everyone on your left side (they're shorter), then call YOU, then call everyone on your right (taller)." Do this for every kid and — magic — they come out in perfect height order. That left-me-right rule is all you need.


Connections

  • Binary Search Tree — the structure whose invariant powers this.
  • Tree Traversals — preorder/postorder/level-order (which do not sort).
  • Validate BST — direct application of this fact.
  • Binary Search — same "left smaller, right bigger" logic on arrays.
  • Structural Induction — the proof technique used here.
  • AVL & Red-Black Trees — keep h=O(logn)h=O(\log n) so traversal stays fast.
  • Kth Smallest Element in BST — stop inorder early at the kth output.

Concept Map

requires

requires

is

expands to

proven by induction

starts proof

assumes subtrees sorted

last < r

first > r

joins lists

yields

BST ordering invariant

Left subtree < node

Right subtree > node

Recursive property

Inorder traversal L-N-R

inorder T = inorder TL + root + inorder TR

Base case: length <= 1

Inductive hypothesis

Inductive step

Concatenation stays sorted

Strictly increasing output

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, BST (Binary Search Tree) ka rule simple hai: har node ke left mein chhote keys aur right mein bade keys hote hain — aur yeh rule recursively poore subtree pe lagta hai, sirf turant wale child pe nahi. Yahi cheez "Search" word ko meaning deti hai.

Ab inorder traversal ka order hai Left → Node → Right (L, N, R). Matlab kisi bhi node pe khade ho, pehle uske saare chhote (left) waale print karo, phir khud ko, phir saare bade (right). Jab har node pe yehi karte ho, toh output apne aap chhote se bade order mein aata hai — sorted! Isko hum induction se prove karte hain: empty/single node toh trivially sorted, aur agar left aur right subtree sorted hain aur root unke beech mein fit hota hai (last-left < root < first-right), toh poora list bhi sorted.

Ek bahut common galti: log sochte hain ki sirf left.key < node < right.key check karna kaafi hai BST validate karne ke liye. Yeh galat hai — deep node ancestor ka bound tod sakta hai. Best trick: inorder chalao aur check karo har element pichle se strictly bada hai ya nahi. Agar kahin nahi, toh BST nahi hai.

Yaad rakhne ka tareeka: "Inorder Rises" — L, N, R se values badhti hain. Time complexity O(n)O(n), space O(h)O(h) height ke barabar. Yehi concept aage Kth smallest element aur Validate BST jaise problems mein direct use hota hai, isliye master kar lo.

Go deeper — visual, from zero

Test yourself — Trees

Connections