Lecture 016

Re-think about the complexity

Balanced Tree: h \in O(\log n)

Self-balancing Tree: a tree remains balanced as we insert new nodes

Goal: additional representation invariants

  1. algorithmically-checkable O(log n)
  2. cheap to maintain O(log n)

Bad Re-balance

Bad Re-balance

AVL Trees

Height invariant: at every node, the height of the left and right sub-trees differ by at most 1

3 possibilities

3 possibilities

How to identify AVL Trees

Insertion in AVL Trees

Approach: two invariant

If a operation requires insertion and rotation, then the height of a tree never change

Left Rotation

Left Rotation

Right Rotation

Right Rotation
These rotation requires the heaviest tree is from outside nodes

Example

Example

Example

Example

Right-Left Rotation

Right-Left Rotation

Double Rotation Summary

Double Rotation Summary

General Strategy

General Strategy

Implementation

Re-balance

Re-balance

Computing Height with O(n)

Computing Height with O(n)

Invariants

Invariants

Traversal

In order traversal

In order traversal

Table of Content