CSE3144 Β· Advanced Data Structures Β· Jul–Nov Semester 2026 Β· Lecture 7 of 36 Β· CO CSE3144.2 Β· Unit II begins

Binary Search Trees, in Depth

The dictionary problem, the BST that solves it, every operation animated β€” and the crack in the design that Lecture 8 repairs.

Dr. Manu ShrivastavaCourse Instructor Β· Consultation Fri 2–5 PM, LHC 308F
40 minutesSession outcome: explain and trace BST search, insertion, and deletion
L7 Β· 00 β€” Agenda 40 min total

Today, minute by minute

The dictionary problem β€” why arrays and lists both fail

00–05

Search fast OR update fast; we need both. The tree is binary search, frozen.

What a BST is, precisely

05–10

The BST property, node anatomy (key, left, right, parent), inorder = sorted.

Animation: building a BST, key by key

10–17

Seven insertions; every walk, every comparison, every parent link.

Animation: search β€” a hit and a miss

17–21

Find 40 in 3 comparisons; fall off the tree looking for 65.

Animation: deletion β€” all three cases

21–29

Leaf, one child, two children (the successor trick).

Animation: the betrayal β€” sorted input

29–33

Lecture 2's employee IDs return; the tree becomes a linked list.

AVL trees: balance, guaranteed

33–38

Balance factors, the height promise, and the cliffhanger: rotations.

Recap + homework

38–40

O(h) is the whole story β€” control h, control everything.

CSE3144 β€” Lecture 7
L7 Β· 01 β€” The need ~5 min

The dictionary problem: three operations, no compromises

A dictionary stores keyed records and must support three operations, repeatedly and in any order: search(k), insert(k), delete(k). Phone contacts, student records by roll number, a compiler's symbol table, your browser history β€” all dictionaries. You already own two structures; watch them each fail one requirement:

Structuresearchinsert / deleteWhere it hurts
Sorted arrayO(log n) β€” binary search βœ“O(n) βœ—Inserting into the middle shifts everything after it. 1 lakh contacts β†’ 1 lakh shifts.
Linked listO(n) βœ—O(1) at a known spot βœ“But finding that spot costs O(n) β€” the pointer must crawl.
What we wantO(log n)O(log n)Fast everything, on data that keeps changing.
The unifying intuition

A BST is binary search, frozen into pointers

Binary search works because each comparison discards half the array. But the array's rigidity ruins updates. So take the decision pattern of binary search β€” "compare with the middle, go left or right" β€” and store it as a structure: the middle becomes the root, the two halves become subtrees, recursively. Searching walks the same path binary search would compute β€” but now inserting is just hanging one new node, no shifting.

Why not the fastest thing ever?

Direct addressing β€” an array indexed by the key itself β€” gives O(1) everything. The price: an array as large as the key universe. Roll numbers like 229301234 would need an array of ~10⁹ slots to store 60 students. The BST spends memory on what you actually store, not on what you might store; hashing (Unit II, later) is the other answer. Trees additionally keep keys in order β€” ranges, nearest-key, sorted listing β€” which hashing never will.

CSE3144 β€” Lecture 7
L7 Β· 02 β€” Definition ~5 min

The BST property β€” one rule, recursively everywhere

Anatomy + the invariant

Each node carries: key Β· left (pointer to left child) Β· right Β· p (pointer to parent β€” the upward link; p[root] = NIL). Every child is linked to its parent from both directions.

For every node x:  all keys in x's left subtree ≀ key[x] ≀ all keys in x's right subtree

Read the fine print: the rule binds entire subtrees, not just children. In the tree alongside, 40 < 50 even though 40 is two levels down on 50's left. This global rule is exactly what makes every operation a single root-to-leaf walk β€” at each node, one comparison eliminates one whole subtree, just like binary search eliminates half the array.

Our running example β€” 7 keys

Free bonus β€” inorder traversal (left subtree, node, right subtree) visits: 20, 30, 40, 50, 60, 70, 80 β€” sorted, automatically. A BST is a sorting of the keys, stored as geometry. This is also your instant correctness check for every exercise: if inorder isn't sorted, the tree is wrong.

The one number that rules everything: every operation we build today walks one path from the root downward, so every operation costs O(h), where h is the tree's height. The entire drama of Unit II β€” AVL, Red-Black, B-Trees β€” is a fight to keep h small. Remember "O(h)" and today's lecture derives itself.

CSE3144 β€” Lecture 7 Β· Definition
L7 Β· 03 β€” Insertion ~7 min

Building the tree, one key at a time

Tree-Insert, simplified
walk from the root, remembering the parent y:
    if new key < current β†’ go left
    else              β†’ go right
when you step onto an EMPTY slot (NIL):
    place the new node there
    p[new] ← y            // child β†’ parent link
    left[y] or right[y] ← new  // parent β†’ child link

Two pointers set, in both directions β€” the new node is stitched in, never inserted "between" anything. No shifting, ever. Cost: the walk, O(h).

How to read the animation

Keys arrive in this order: 50, 30, 70, 20, 40, 60, 80. At each step the amber nodes are the comparison path walked, the teal node is the newly linked child β€” watch its connector tick attach to the parent β€” and dotted boxes are empty slots (NIL): real places where a future key can land.

Interactive β€” seven insertions, every comparison shown
CSE3144 β€” Lecture 7 Β· Insertion
L7 Β· 04 β€” Search ~4 min

Search: the same walk β€” a hit and a miss

Tree-Search
Tree-Search(x, k):
    if x = NIL or k = key[x]: return x
    if k < key[x]: return Tree-Search(left[x], k)
    else:          return Tree-Search(right[x], k)

Each comparison discards an entire subtree β€” never to be looked at again. Running time: O(h), one node per level.

The insight the miss teaches

Searching for an absent key doesn't fail randomly β€” it walks to exactly the empty slot where that key would be inserted. Search and insert are the same walk with different endings. (That's why insert was so easy.)

Interactive β€” search 40 (present), then 65 (absent)
CSE3144 β€” Lecture 7 Β· Search
L7 Β· 05 β€” Deletion ~8 min

Deletion: three cases, and a beautiful trick for the hard one

Case 0 β€” leaf

No children: just unlink it from its parent. Nothing else moves.

Case 1 β€” one child

Splice it out: the parent adopts the only child directly (p[child] ← p[x]). The chain closes over the gap.

Case 2 β€” two children

Can't unlink β€” two orphaned subtrees! Trick: overwrite x's key with its inorder successor (the smallest key in x's right subtree), then delete the successor β€” which never has a left child, so it's always Case 0 or 1.

Interactive β€” delete 20 (leaf), then 30 (one child), then 50 (two children)

Why the successor? It is the key that sits immediately after x in sorted order β€” so promoting it preserves the BST property with zero other changes. (The inorder predecessor β€” largest in the left subtree β€” works symmetrically.) All three cases: one walk + O(1) pointer surgery = O(h).

CSE3144 β€” Lecture 7 Β· Deletion
L7 Β· 06 β€” The betrayal ~4 min

Feed it sorted keys, and the tree stops being a tree

Lecture 2's case, replayed for real

Everything today cost O(h) β€” and we quietly hoped h β‰ˆ log n. For random insertion order the height is provably O(log n) on average (the argument mirrors quicksort's average recursion depth). But real data is rarely random: auto-increment IDs, roll numbers, timestamps arrive sorted. Watch what our insert algorithm does to them β†’

The bill, at scale
n keysh, balancedh, sorted input
726
1,000~10999
1,000,000~20999,999

Same structure, same code β€” a 50,000Γ— slowdown, from input order alone.

Interactive β€” insert 10, 20, 30, 40, 50, 60 (already sorted)
CSE3144 β€” Lecture 7 Β· Degeneration
L7 Β· 07 β€” AVL trees ~5 min

AVL: don't hope for balance β€” enforce it

The definition (Adelson-Velsky & Landis, 1962)

Give every node a balance factor:

bf(x) = height(left subtree) βˆ’ height(right subtree)

An AVL tree is a BST in which every node has bf ∈ {βˆ’1, 0, +1}. Perfectly equal heights aren't demanded β€” siblings may differ by one β€” just never more.

The payoff, guaranteed: this local rule forces h ≀ 1.44 logβ‚‚(n+2) β€” whatever order the keys arrive in. Sorted, reverse-sorted, adversarial: h stays O(log n), so search, insert, and delete stay O(log n). The hope becomes a contract.

Balance factors, annotated on our two trees

The balanced tree: every bf is 0 β€” a valid AVL tree. The sorted-input chain: bf values βˆ’5, βˆ’4, βˆ’3, βˆ’2 (violations highlighted) β€” illegal at almost every node. An AVL tree would have refused to let this shape ever form.

The cliffhanger β€” how does it refuse?

Insertion happens exactly as today β€” then the tree walks back up the insertion path, updating balance factors. The moment some node hits bf = Β±2, the tree performs a rotation: an O(1) pointer surgery that lifts the deep side up and restores every bf to {βˆ’1, 0, +1}, while preserving the BST property. One rotation (sometimes a double) fixes everything. Next lecture: the four rotation cases β€” LL, RR, LR, RL β€” each animated the way today's operations were.

CSE3144 β€” Lecture 7 Β· AVL
L7 Β· 08 β€” Recap & what's next ~2 min

Three takeaways

Next β€” Lecture 8

AVL Rotations, Insertion & Deletion

LL, RR, LR, RL β€” the four repairs, animated; then full AVL insert/delete traces with balance factors updating live.

Homework β€” bring to Lecture 8
  • Build the BST for insertions 55, 25, 80, 15, 40, 70, 95, 30, 45; draw it, then write its inorder traversal to verify.
  • On your tree: delete 15, then 25, then 55 β€” identify which case each is, show the tree after each.
  • For keys 1–7: give one insertion order producing height 2, and count how many orders produce height 6.
  • Compute bf for every node of your homework tree. Is it AVL?
  • Search 47 in your tree: list every comparison, and state where 47 would be inserted.
  • Reading: CLRS ch. 12; Weiss Β§4.1–4.4.
CSE3144 β€” Lecture 7

Questions?

Dr. Manu Shrivastava β€” LHC 308F β€” Friday 2:00–5:00 PM

Next: Lecture 8 β€” Rotations: the repair kit. When a balance factor hits Β±2, an O(1) "rotation" restores balance without breaking the BST property.