3.4.5 · D4Trees

Exercises — BST — inorder gives sorted order

2,598 words12 min readBack to topic

The two trees we reuse across problems:

Figure — BST — inorder gives sorted order

We call the left one Tree A and the right one Tree B. Look at them now — every exercise below points back to this figure.


Level 1 — Recognition

Recall Solution

Inorder = Left, Node, Right applied recursively. Dive to the leftmost node first (smallest), then climb. Why: every node is emitted only after its entire smaller-left family. The list is sorted — as guaranteed for any BST.

Recall Solution

False. Postorder is Left, Right, Node — the node comes last, so the root of Tree A (8) would be printed at the very end, not in its sorted slot. Only inorder (L, N, R) sorts a BST. See Tree Traversals for the others. Postorder of Tree A: — clearly not sorted.


Level 2 — Application

Recall Solution

Dive-left pushes, pop emits, then go right and dive-left again.

Step Stack (bottom→top) Pop → emit Then go right to
1 8, 3, 1 1 none
2 8, 3 3 6 (push 6)
3 8, 6 6 none
4 8 8 10 (push 10)
5 10 10 14 (push 14)
6 14 14 none

Output: . Why the stack? It remembers the postponed "visit node + go right" work of each ancestor while we dived left.

Recall Solution

Inorder emits in increasing order, so the -th emitted value is the -th smallest. Count emissions and stop at the 3rd: This is exactly the early-stop trick of Kth Smallest Element in BST — you never touch 8, 10, 14.

Recall Solution

Insert one by one, each key going left if smaller, right if larger, from the root down:

  • 5 → root
  • 2 < 5 → left of 5
  • 8 > 5 → right of 5
  • 1 < 5, < 2 → left of 2
  • 3 < 5, > 2 → right of 2
      5
     / \
    2   8
   / \
  1   3

Inorder = — sorted, as the invariant promises, regardless of insertion order.


Level 3 — Analysis

Recall Solution

No. Run inorder: dive left of 5 → 3; emit 3; back to 5, emit 5; go right to 7, dive left → 4; emit 4; emit 7. Here but 5 comes before 4 — the sequence is not increasing, so it is not a BST. The offender: node 4 sits in 5's right subtree yet is smaller than 5. This is the classic Validate BST pitfall.

Recall Solution

Every node inherits an allowed open interval from its ancestors:

  • Root 5: interval .
  • Right child 7: must be , so interval .
  • 7's left child 4: must be (from the ancestor 5) and , so interval .

But . The local parent–child check only tested and forgot the inherited lower bound coming from the grandparent. Inorder catches this automatically because 4's position after 5 exposes the descent.

Recall Solution
  • Time: each of nodes is visited once → , always.
  • Space: the recursion/stack depth equals the tree height .
    • Balanced: .
    • Skewed (a straight line, e.g. inserting ): , so space .

Why check not ? With distinct keys a valid BST is strictly increasing; using would wrongly accept two equal adjacent keys.


Level 4 — Synthesis

Recall Solution

Preorder's first element is the root → 6. In the inorder list, everything left of 6 is the left subtree , everything right is the right subtree .

  • Recurse left on inorder with the next preorder items : root 4, left child 2.
  • Recurse right on inorder : single node 8.
      6
     / \
    4   8
   /
  2

Check: inorder ✓. Why it works: inorder splits left/right around each root; preorder hands us the roots top-down. Together they pin down a unique tree.

Recall Solution

Inorder P ; inorder Q . Merge like the merge step of mergesort (this is the Binary Search / sorted-array world): (the two 4's collapse to one). A two-pointer merge of lists of size and does at most comparisons. Why inorder first? It converts each tree into a sorted list for free, so the hard part (sorting) is already done.

Recall Solution

The successor of a node is the smallest key in its right subtree (if it has one).

  • Node 8 has right subtree rooted at 10; its smallest key is the leftmost node there = 10.
  • Node 6 has no right child, so its successor is the lowest ancestor whose left subtree contains 6: climbing 6 → 3 → 8, the first turn that is a "left" step is 3 being the left child of 8, so the successor is 8.

Cross-check with the sorted list : after 8 comes 10 ✓, after 6 comes 8 ✓.


Level 5 — Mastery

Recall Solution

Use Structural Induction on the tree.

Base case. Empty tree or single node: vacuously/trivially a BST. ✓

Inductive hypothesis. Assume every proper subtree whose inorder is strictly increasing is itself a BST.

Inductive step. Let have root , left subtree , right subtree . The inorder of is Given this whole sequence is strictly increasing:

  1. Block appears entirely before , so every key in is .
  2. Block appears entirely after , so every key in is .
  3. Block is strictly increasing (a contiguous slice of an increasing sequence), so by IH is a BST. Same for .

Conditions (1)–(3) are exactly the BST definition at , recursively satisfied. Hence is a BST.

This is why validation-by-inorder is correct, not just a heuristic — it powers Validate BST.

Recall Solution

The largest key is the rightmost node. Two cases for the second largest:

  • Case A: if the largest (rightmost) node has a left subtree, the 2nd largest is the rightmost node of that left subtree.
  • Case B: if the rightmost node has no left child, the 2nd largest is its parent.

Walk right from the root, keeping a parent pointer:

def second_largest(root):
    if root is None or (root.left is None and root.right is None):
        return None                 # fewer than 2 nodes
    parent, cur = None, root
    while cur.right:                # go to the largest
        parent, cur = cur, cur.right
    if cur.left:                    # Case A
        cur = cur.left
        while cur.right:
            cur = cur.right
        return cur.key
    return parent.key               # Case B

Only one root-to-leaf path is walked → time, space.

Tree A: rightmost is 14 (8 → 10 → 14), parent = 10. 14 has no left child → Case B → answer 10. Check against sorted list : 2nd largest is 10 ✓.

Recall Solution

Each new key is larger than all before it, so it becomes the right child of the previous — a right-skewed line (essentially a linked list):

1
 \
  2
   \
    3
     \
      4
       \
        5

Height . Inorder is still (correct!), but the recursion/stack depth is , and search degrades to per operation. Fix: a self-balancing tree (AVL / Red-Black) enforces , keeping traversal and search fast while preserving the exact same sorted inorder.


Connections

  • Parent: inorder gives sorted order — the fact every exercise rests on.
  • Binary Search Tree — the invariant under test.
  • Tree Traversals — why preorder/postorder do not sort (L1.2).
  • Validate BST — L3 and L5.1 are its correctness core.
  • Binary Search — the sorted-array world (L4.2 merge).
  • Structural Induction — proof engine for L5.1.
  • Kth Smallest Element in BST — the early-stop trick (L2.2, L5.2).
  • AVL & Red-Black Trees — the fix for L5.3 degeneration.