No programming assignment this week!
Instead: short take-home quiz on binary search trees
add/remove/find in $O(\log n)$ timeadd/remove operation in $O(\log n)$ time?add to restore balanceremove?Case 1: Leaf
Case 2: Single-child
Case 3: Two-child
What is height of root after restructuring?
Restructuring may again cause imblance! Must continue upwards.
After remove(x), iterate over removed node’s ancestors upwards:
What is running time?
We can modify add/remove such that
So
add/remove/find operations happen in $O(\log n)$ time!Compare performance of BST (as in Assignment 06) and AVL tree implementation
Tests:
Time to add elements (ms):
BST: 770
AVL: 601
Heights:
BST: 45
AVL: 22
Time to find elements (ms):
BST: 120
AVL: 88
Time to remove elements (ms):
BST: 89
AVL: 137
Time to add Shakespeare's vocabulary (ms):
BST: 287
AVL: 246
Heights:
BST: 36
AVL: 17
Time to add words from dictionary (ms):
BST: 639
AVL: 2
Heights:
BST: 9999
AVL: 13
(Dis)advantages of BST vs AVL tree?
2 Ingredients:
AVL trees give efficient worst-case performance
add, remove, find all in $O(\log n)$ timePerformance between BST vs AVL trees depends on usage
Another Tree Representation:
Goal. Implement a priority queue with $O(\log n)$-time operations
Exercise. How could this goal be achieved with an AVL tree?
comparable elemements
Goal. Use & maintain these properties for an efficient implementation of a priority queue:
add(x, p)min()removeMin()$T$ a binary tree
$T$ has the heap property if for every node storing value $v$ with children $u$ and $w$, we have $v \leq u$ and $v \leq w$.
If $T$ has the heap property, what can we say about the value of the root?
$T$ is a complete binary tree of depth $D$ if:
If $T$ is a complete binary tree, where can we add a node to maintain completeness?
If $T$ is a complete binary tree, what nodes can we remove and maintain completeness?
If $T$ is a complete binary tree with $n$ nodes, what is its depth?
A binary tree $T$ storing comparable elements is a binary heap if:
Given a binary heap $T$, how can we implement min()?
Given a binary heap $T$, how can we add an element?
w
w < w.parent, swap w and w.parent
w
w < w.parent, swap w and w.parent
w
w < w.parent, swap w and w.parent
Given a binary heap $T$, how can we removeMin?
w to rootw > some child, v = smaller child
v and w valuesw to rootw > child, v = smaller child
v and w valuesw to rootw > child, v = smaller child
v and w valuesPreviously:
Complete binary trees have much more predictable structure
For an index $i$, what is the index of $i$’s left child? Right child?
For an index $i$, what is the index of $i$’s parent?
Why didn’t we use arrays to represent (non complete) binary trees?
Implement a priority queue using a binary heap!