AVL Trees Flashcards
1
Q
AVL Trees
A
- type of binary search tree with the additional invariant that tree is balanced
- implemented just like a bst, with additional “rotation” operations
- each time you insert or delete an item, you balance nodes along path of insertion/deletion
2
Q
rotation
A
- operation used to balance a tree
- mainly involves changing pointers
- shift the root and the left (or right) child over, while maintaining the relative order of the subtrees
2 types of rotation
- left rotation
- right rotation
3
Q
AVL
balancing tree
A
- process of restoring the balanced invariant
Steps (left-heavy):
- Check balance factor of root node and children
- If bf(root) == -2, tree is left-heavy
- If bf(left) < 0 or bf(left) == 0 → case: left-left
- Perform right rotation on root
- If bf(left) > 0 → case: left-right
- Perform left rotation of left child
- Perform right rotation on root
- Use reverse logic for right-heavy trees
4
Q
height of a node
A
- number of edges from a node to its furthest leaf
- height(node) = max(left subtree, right subtree) + 1
- where the empty tree has height of -1
- the height of a tree is the height of the root
5
Q
balance factor
A
- balance factor (bf) of a tree is the difference in the heights of both subtrees
- bf(node n) = height(right subtree) - height(left substree)
6
Q
balanced tree
A
- a tree where the heights of the left and right subtrees differ by no more than 1
- a tree is balanced if balance factor is {-1, 0, 1}