Professor Abdul-Quader
Lesson 7 (Tree Rotations / AVL Trees)
Four presentations today.
Project 1 is due Sunday. Questions?
L = root.left
root.left = L.right
L.right = root
return L
Makes L the new root of this subtree.
Similar idea:
R = root.right
root.right = R.left
R.left = root
return R
Draw the trees we obtain after the following sequence of operations:
What does an “unbalanced” tree look like?
Some unbalanced trees can be rebalanced easily:
Forget about the code for a bit. What should a self-balancing tree do when we insert in the following order: 1, 2, 3, 4, 5, 6, 7?
Draw the pictures of the BSTs that result. When do we trigger a “rebalancing”?
Again:
Right-right: rotate left
Right-left: rotate right around 20, then left around 10.
height(subtree.right.right) >= height(subtree.right.left)
private TreeNode<T> balance(TreeNode<T> subtree) {
int balance = height(subtree.left) - height(subtree.right);
if (balance > 1) {
// left-left
if (height(subtree.left.left) >= height(subtree.left.right)) {
subtree = rotateRight(subtree);
} else {
// left-right
// left rotation turns this into left-left
subtree.left = rotateLeft(subtree.left);
// right rotation rebalances
subtree = rotateRight(subtree);
}
} else if (balance < -1) {
// right-right or right-left?
// do the opposite as above
}
// update height
subtree.height = 1 + Math.max(height(subtree.left), height(subtree.right));
return subtree;
}
In the above video, I go through the proof that all the operations are \(O(\log(n))\).
Given a tree T, output its nodes in level-order. That is, output the root first, then output the root’s children, then the grandchildren, etc.
Hint:
Implement a method in the AVL Tree class which returns a List of items in sorted order:
Asymptotic running time (if the tree has \(N\) elements)?
Asymptotic running time of the following: