Lecture 12: Midterm #1 Review and AVL Trees
This lecture we talked about the midterm we just took as well as implementing the add method in an AVL tree
Scribes:
- Neal Malani
Midterm 1
Problem 1 A
- Mostly marked “best answer”, but not all “correct answers”
- Property
- f = O(g), g(n) < = h(n)
- f = O(h)
- For f = O(n2) means there exists N and C such that for n >= N, f(n) < = C * n2
- Property
Problem 1 B
- foo = O(log n) bar = O(n) not O(log n) Empirical running time?
- Do not know constant factors
- 1000000 log n < 0.001 n for large n
- O is only for worst-case, not necessary what typically happens
- Do not know constant factors
Problem 3 A
- Stack: resize for push to increase capacity, pop to decrease
- Push/pop O(n) is worst case
- Amortized cost?
- If pop and resize to N1 then next decrease of N/2 will be cost of Cn/2
- Each pop pay 1/(N/2) fraction of CN/2 = O(1) so amortized cost is O(1)
Problem 3 B
- What about pushes together w/ pops?
- Push: size N → N + 1, capacity N → 2N
- Pop: size N+1 → N, capacity 2N → N
- Repeat 1 and 2
Problem 4
- Multi S Set
- Sequence of elements in an array w restrictions
- Find multiplicity of elements in O(log n)
- How to find # of x’s
- Use binary search to go through the entire array to search for x
- Once x is found, split up the left and the right halves in order to conduct binary search for the first and last values of when x appears
- Once found the indices of those two values, subtract them from each other and add one in order to get the multiplicity
- Sequence of elements in an array w restrictions
AVL Trees
- Last time
-
T a binary search tree and node v is balanced if h(left child) - h(right child) <= 1 - T is a AVL tree if all nodes are balanced
-
- Claim: if T is an AVL tree w/ n nodes, then h(T) = O(log n)
- Add, remove, find have running time O(log n)
- Note: If T is AVL then add/remove could destroy AVL property
- Goal: Supplement the add and remove operations efficiently maintain balance
- Dealing with add
- Add creates imbalance
- Adding node w:
- Z = first ancestor of w that is unbalanced
- Y = child of z toward w
- X = child of y toward w
- Make x the new root and y its left and z its right child
- Why would the result be a BST?
- Relative order is maintained
- Adding node w:
- What is the running time?
- O(1) once z is located
- Finding z efficiently
- Each node stores height as variables
- When add/remove/restructure we update heights
- O(height) b/c only need to update ancestors
- Add creates imbalance