# Lecture 11: Binary Search Tree and AVL Trees

Will include how to print BST elements and will continue discussion on AST Trees

Scribes:

- Neal Malani

## Accessing Elements in BST

### Helpful tool: print contents of BST in sorted order

**Q**: How could we print the contents of a BST in sorted order?

- One approach
- Find the smallest element and print it
- Keep going left

- Find the next element and print it
- Messy approach 1
- Remove the smallest element
- Find the new smallest element

- Messy approach 2
- If there is a right child, go right, then left until there are no more left children. There will be the next smallest element
- If no right child, look at the parent
- Gets messy!

- Messy approach 1

- Find the smallest element and print it
**Idea**: Use BST property that everything to the left of the root is smaller and everything right of the root is bigger- Observation
- If we print
- Stuff on the left side of the root
- The root
- Stuff on the right side of the root

- Recursion
- printInOrder()
- to print everything, call it on the root

- printInOrder()

- If we print

- Observation

1
2
3
4
5
6
7
8
9
10
11
12

public class Node{
private void printInOrder(){
if (left != null){
left.printInOrder();
System.out.println(value);
}
if (right != null){
right.printInOrder();
System.out.println(value);
}
}
}

- Types of traversals
- In order traversal
- Process left subtree
- Process self
- Process right subtree

- Preorder traversal
- Process self
- Process left subtree
- Process right subtree

- Postorder traversal
- Process left subtree
- Process right subtree
- Process self

- In order traversal
- Post order traversals can help with finding height of a binary search tree
- height(v) = 1 + max(height left, height right)

## AVL Trees

- Recall AVL Trees
- Given v, a node, in a tree, say that v is (height) balanced if the height of the right child and the height of the left child differ at most by 1
- An AVL tree is a tree in which all nodes are balanced

- Fact: If T is an AVL Tree containing n nodes, then h(T) = Big O(log n)
- Find, add, and remove take time Big O(log n)

**Question**: Start with an AVL tree T and add an element. How can we ensure the updated tree is AVL?- Node w = node added
- Node z = first unbalanced ancestor of node w
- Node y = child of z on the path to w
- Node x = child of y on the path to w

- Adding one node increased height by at most 1 <= h + 2
- Also, >= h + 2 because there is an imbalance

- Take the middle value, x, and make it the root

## Things to think about

- Does this restore the balance?
- Does it maintain the BST property?
- What is the running time?