Professor Abdul-Quader
22 February 2021
Today:
if (root == null) {
return false;
}
int comparison = item.compareTo(root.data);
if (comparison == 0) {
return true;
} else if (comparison < 0) {
return contains(root.left, item);
} else {
return contains(root.right, item);
}
private T findMin(TreeNode<T> subtree) {
if (subtree == null) {
return null;
}
while (subtree.left != null) {
subtree = subtree.left;
}
return subtree.data;
}
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
What does an “unbalanced” tree look like?
Some unbalanced trees can be rebalanced easily:

// psuedocode
private TreeNode<T> insert(T item, TreeNode<T> subtree) {
// code to insert
int balance = height(subtree.left) - height(subtree.right);
if (balance > 1) {
// left-left or left-right?
} else if (balance < -1) {
// right-right or right-left?
}
}
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”?