CS226 - Day 19 - Spring 2013 BALANCED BINARY SEARCH TREES (BBSTs) - balanced binary tree: |hl-hr| <= 1 for every node (recursively) where hl denotes height of left subtree, hr the height of the right subtree - balance factor BF(t) of node t is hl-hr. - in a balanced tree -1 <= BF(t) < = 1 for every node t - height of tree is O(log N) with this property: - let n(h) be the min # nodes in height h BBST tree - n(h) = n(h-1) + n(h-2) + 1, n(0)=0, n(1)=2, n(2)=4. - fibonacci progression - find lower bound on n(h) = 1 + n(h-1) + n(h-2) n(h) = 1 + n(h-1) + n(h-2) > 2 n(h-2) > 4 n(h-4) > 8 n(h-6) > 2^i n(h-2i) set h-2i = 2 -> i = h/2 - 1 > 2^(h/2-1) * 4 > 2^(h/2) 2 log (n(h)) > h, and N >= n(h) by definition therefore, height is O(log N) AVL Trees (Adelson-Velskii & Landis) ------------------------------------------------------------------------ - provide a way to make a balanced binary search tree - must maintain height balance property when insert & remove - insert, search operations are O(h) = O(log N) - can delete in O(log N) too - insertion: - insert item as in binary search tree - starting with new node, go up to update heights - if find a node that has become unbalanced - do restructure to rebalance - rebalance reduces height of subtree by 1, so no need to propagate up - O(log n) - removal: - start as w/binary search tree - ancestor of deleted node (not replaced node) may become unbalanced - go up from deleted node to find first unbalanced - do rotation - may reduce the height of the subtree - propagate/check upward to root! - O(log n) Restructuring the tree with rotations to maintain the balance: - do single or double rotation (abstract diagrams in Weiss text) - http://en.wikipedia.org/wiki/AVL_tree for diagrams - rotation types: single LL, single RR, double LR, double RL - each double is two singles: double LR = RR then LL, double RL = LL then RR Single RR 30 25 / \ / \ 25 D 20 30 / \ / \ / \ 20 C => A B C D / \ A B Single LL 20 25 / \ / \ A 25 20 30 / \ => / \ / \ B 30 A B C D / \ C D Double RL (rotate 2-3 right, then 1-2 left) 1 2 \ => / \ 3 1 3 / 2 Double LR (rotate 7-8 left, then 8-10 right) 10 8 / => / \ 7 7 10 \ 8 - implement: use recursion to rebalance the tree - so overall will go down tree to search/insert (push recursion stack) and then back up to rebalance (pop recursion stack) - unbalance indicator is really a height change indicator