3.4.5 · D3Trees

Worked examples — BST — inorder gives sorted order

2,420 words11 min readBack to topic

You have already met the big idea in the parent note: in a Binary Search Tree, visiting Left → Node → Right (inorder) spits keys out in increasing order. This page does one job: it walks every kind of tree you could be handed and traces the traversal by hand, so no shape ever surprises you.

Before we trace anything, let us agree on the plain-word meaning of the words we will use, because we will use them a LOT.


The scenario matrix

Here is the full list of shapes a BST-inorder question can be. Every worked example below is tagged with the cell it covers, so by the end every row is ticked.

# Case class What makes it tricky Covered by
A Empty tree (0 nodes) Degenerate — output must be [] Ex 1
B Single node Base case of the proof Ex 1
C Balanced tree, both children everywhere The "normal" case Ex 2
D Left-skewed (only left children) Looks like a linked list going down-left Ex 3
E Right-skewed (only right children) Linked list going down-right Ex 3
F Negative & mixed-sign keys Ordering must respect number line, not size Ex 4
G Duplicate keys present Strict < policy — where does the twin go? Ex 5
H "Is it even a BST?" (validation) A deep node violates a far ancestor Ex 6
I Real-world word problem Translate a story into left/right Ex 7
J Exam twist — stop early (Kth smallest) Don't finish the whole traversal Ex 8

Case A & B — the degenerate floor


Case C — the balanced everyday tree

Figure — BST — inorder gives sorted order

Cases D & E — the two skewed sticks

Figure — BST — inorder gives sorted order

Case F — negatives and mixed signs


Case G — duplicate keys


Case H — the sneaky invalid tree

Figure — BST — inorder gives sorted order

Case I — a real-world word problem


Case J — the exam twist: stop early


Recall One-line summary of the whole matrix

Whatever the shape — empty, skewed, negative, duplicated, invalid, or story-dressed — inorder's job is always the same: ::: walk L-N-R, and every node prints only after its entire smaller-left family, so the output rises (or, on an invalid tree, fails to rise and betrays the violation).


Connections

  • Parent topic — the theory these examples exercise.
  • Binary Search Tree — the invariant every trace relies on.
  • Tree Traversals — why preorder/postorder do not sort (see Ex 7).
  • Validate BST — Case H made concrete.
  • Kth Smallest Element in BST — Case J's early-stop trick.
  • AVL & Red-Black Trees — fix the skew cost of Case D/E.
  • Structural Induction — proves the base case of Ex 1.
  • Binary Search — same left-smaller/right-bigger logic on arrays.