150 likes | 235 Views
Balanced Trees. AVL Trees. Binary Search tree with a balance condition Why? For every node in the tree, the height of its left and right subtrees must differ by at most 1 Ensures O(log N) depth. AVL Tree Insertion. Must maintain balance condition Insert as in BST
E N D
AVL Trees • Binary Search tree with a balance condition • Why? • For every node in the tree, the height of its left and right subtrees must differ by at most 1 • Ensures O(log N) depth
AVL Tree Insertion • Must maintain balance condition • Insert as in BST • Follow path back to root rotating at nodes that do not meet balance condition
Cases of Imbalance • Left subtree of left child • Right subtree of right child • External
Cases of Imbalance • Right subtree of left child • Left subtree of right child • Internal
Single Rotation k2 k1 k2 k1 Z X Y Z X Y
Double Rotation k2 k3 k3 k1 Z k1 Z k1 k3 X Y X k2 X A B Z B A • Rotate k1 and k2 • Rotate k2 and k3
Splay Trees • Goal: M operations take O(MlogN) time • Some operations may take O(N) time but cost is amortized • After each access, rotate node to root • Helps to balance an unbalanced tree • Next access will be fast (assumption – items are accessed frequently)
Zig-zag – Access X X G P Z P G X X X A B Z B A
Zig-zig – Access X G X P X P Z X A G B X A B Z
B-Trees • Entire tree may not fit in memory • 10,000,000 records, height of 25, search of 4 seconds (page 165) • Want a shorter, bushier tree • M-ary tree, tree with M-way branching • height of logMN
B-Tree Properties • The data items are stored at leaves. • The nonleaf nodes store up to M-1 keys to guide the searching; key i represents the smallest key in subtree i+1 • The root is either a leaf or has between two and M children. • All nonleaf nodes (except the root) have between ceil(M/2) and M children. • All leaves are at the same depth and have between ceil(L/2) and L children, for some L.
Example Tree, L=5 M=5 |41| |66| |87| | | |8| |18| |26| |35 | |48| |51| |54| | | |72| |78| |83| | | |92| |97| | | | | 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 31 32 35 36 37 38 39 41 42 44 46 48 49 50 51 52 53 54 56 58 59 66 68 69 70 72 73 74 76 78 79 81 83 84 85 87 89 90 92 93 95 97 98 99
Insertion • If leaf is not full, add new item • If leaf is full, split leaf into two each with ceil(L/2) items • also need to update parent(s) • May need to split all the way up the tree • Cannot split root, but can create new root with 2 children • Also, may put child up for adoption – move to neighbor if room
Deletion • Remove item • if number of children below min, merge • percolate up tree if necessary • if root has only 1 child, remove root and make its child the new root