Balanced Search Trees l BST efficient lookup insertion
Balanced Search Trees l BST: efficient lookup, insertion , deletion Ø Average case: O(log n) for all operations since find is O(log n) [complexity of insert after find is O(1), why? ] Ø Worst case is bad, what's big-Oh? What's the tree shape? Ø If we can guarantee log n in worst case, why might this be preferable to hashing? Properties of search tree? l Balanced Search trees Ø Use rotations to maintain balance, different implementations rotate/rebalance at different times Ø AVL tree is conceptually simple, bookkeeping means coefficient for big-Oh is higher than other ideas Ø Red-black tree harder to code but good performance: basis for Java map classes and most C++ map classes CPS 100 8. 1
Balance trees we won't study l B-trees are used when data is both in memory and on disk Ø File systems, really large data sets Ø Rebalancing guarantees good performance both asymptotically and in practice. Differences between cache, memory, disk are important l Splay trees rebalance during insertion and during search, nodes accessed often more closer to root Ø Other nodes can move further from root, consequences? • Performance for some nodes gets better, for others … Ø CPS 100 No guarantee running time for a single operation, but guaranteed good performance for a sequence of operations, this is good amortized cost (vector push_back) 8. 2
Balanced trees we will study l l l Both kinds have worst-case O(log n) time for tree operations AVL (Adel’son-Velskii and Landis), 1962 Ø Nodes are “height-balanced”, subtree heights differ by 1 Ø Rebalancing requires per-node bookkeeping of height Ø http: //www. seanet. com/users/arsen/avltree. html Red-black tree uses same rotations, but can rebalance in one pass, contrast to AVL tree Ø In AVL case, insert, calculate balance factors, rebalance Ø In Red-black tree can rebalance on the way down, code is more complex, but doable Ø STL in C++ uses red-black tree for map and set classes Ø Standard java. util. Tree. Map/Tree. Set use red-black CPS 100 8. 3
Rotations and balanced trees l l Height-balanced trees Ø For every node, left and right subtree heights differ by at most 1 Ø After insertion/deletion need to rebalance Ø Every operation leaves tree in a balanced state: invariant property of tree Find deepest node that’s unbalanced then make sure: Ø On path from root to inserted/deleted node Ø Rebalance at this unbalanced point only CPS 100 Are these trees heightbalanced? 8. 4
Rotation to rebalance N l N C A B C When a node N (root) is unbalanced height differs by 2 (must be more than one) Ø Change N->left • do. Left Ø Change N->left->right • do. Left. Right Ø Change N->right->left Tree * do. Left(Tree * root) • do. Right. Left { Tree * new. Root = root->left; Ø Change N->right • do. Right root->left = new. Root->right; new. Root->right = root; l First/last cases are symmetric return new. Root; l Middle cases require two rotations } Ø First of the two puts tree into do. Left or do. Right CPS 100 8. 5
Rotation up close (do. Left) l Why is this called do. Left? Ø N will no longer be root, new value in left->left subtree Ø Left child becomes new root l Rotation isn’t “to the left”, but rather “brings left child up” Ø do. Left. Child. Rotate? N N C A B C Tree * do. Left(Tree * root) { Tree * new. Root = root->left; root->left = new. Root->right; new. Root->right = root; return new. Root; } CPS 100 8. 6
Rotation to rebalance ? ? ? N l N C A A B B C l Suppose we add a new node in right subtree of left child of root Ø Single rotation can’t fix Ø Need to rotate twice First stage is shown at bottom Ø Rotate blue node right • (its right child takes its place) This is left child of unbalanced Tree * do. Right(Tree * root) { Tree * new. Root = root->right; root->right = new. Root->left; new. Root->left = root; return new. Root; } Ø C A B 1 CPS 100 B 2 B 1 A B 2 8. 7
Double rotation complete l Calculate where to rotate and what case, do the rotations Tree * do. Right(Tree * root) { Tree * new. Root = root->right; root->right = new. Root->left; new. Root->left = root; return new. Root; } Tree * do. Left(Tree * root) { Tree * new. Root = root->left; root->left = new. Root->right; new. Root->right = root; return new. Root; } CPS 100 C A B 1 B 2 C A B 1 A B 2 C 8. 8
AVL tree practice Insert into AVL tree: Ø 18 10 16 12 6 3 8 13 14 Ø After adding 16: do. Left. Rightdo. Left l 18 18 10 do. Right 16 10 10 18 16 16 10 10 18 6 18 12 10 After 16 3, do. Left on 16 10 10 6 16 16 10 Ø 18 18 12 6 3 6 16 12 18 3 16 8 12 18 3 CPS 100 8. 9
AVL practice: continued, and finished l l After adding 13, ok After adding 14, not ok Ø do. Right at 12 6 3 10 16 8 12 10 18 6 13 14 3 16 8 13 12 CPS 100 18 18 14 8. 10
Trie: efficient search of words/suffixes l A trie (from retrieval, but pronounced “try”) supports Ø Insertion: a word into the trie (delete and look up) Ø These operations are O(size of string) regardless of how many strings are stored in the trie! Guaranteed! l In some ways a trie is like a 128 (or 26 or alphabet-size) tree, one branch/edge for each character/letter Ø Node stores branches to other nodes Ø Node stores whether it ends the string from root to it l Extremely useful in DNA/string processing Ø monkeys and typewriter simulation which is similar to some methods used in Natural Language understanding (n-gram methods) CPS 100 8. 11
Trie picture and code (see trie. cpp) l l To add string Ø Start at root, for each char create node as needed, go down tree, mark last node To find string Ø Start at root, follow links a c s n h a r a s t r p a c d o • If NULL, not found Check word flag at end To print all nodes Ø Visit every node, build string as nodes traversed What about union and intersection? Ø l l CPS 100 Indicates word ends here 8. 12
Boggle: Tries, backtracking, structure Find words on 4 x 4 grid l Adjacent letters: Ø f g h i j m l No re-use in same word k l Two approaches to find all words l Try to form every word on board Ø Look up prefix as you go • Trie is useful for prefixes l l H E S I W L B D A B I M Z E V S Look up every word in dictionary Ø For each word: on board? ZEAL and SMILES CPS 100 8. 13
Search board for word: trieboggle. cpp void search(int row, int col, Trie. Node * t, string so. Far) // pre: row, col are on board, so. Far is valid prefix, // string constructed on board during current search // t represents the path in the trie of so. Far { if (!legal(row, col) || is. Visited(row, col) ) return; char ch = my. Board[row][col]; // check if still a prefix Node * child = t->links[ch]; if (child == 0) return; // NOT a prefix, stop // still prefix, continue mark. Visited(row, col); // don’t revisit string new. Prefix = word + ch; if (child->is. Word) cout << new. Prefix << endl; } CPS 100 do. Find(row-1, col-1, child, new. Prefix); do. Find(row-1, col+1, child, new. Prefix); un. Visit(row, col); // // up-left straight up still 5 more calls now ok to revisit 8. 14
Search for all words: boggle. cpp bool word. Found(const string& s, const Point& p) // pre: s is suffix of word searched for, prefix so far // is found and last letter of found prefix at p(row, col) { if (s. length() == 0) return true; // no more suffix, done tvector<Point> points = my. Points. For(s[0]); } for(int k=0; k < points. size(); k++) { Point next. P = points[k]; if (Is. Adjacent(p, next. P) && ! is. Visited(next. P)) { mark. Visited(next. P); // don’t visit again if (word. Found(s. substr(1, s. length()-1), next. P)) { return true; } un. Visit(next. P); // ok to visit again } } return false; // tried to find s, failed in all attempts CPS 100 8. 15
Danny Hillis l The third culture consists of those scientists and other thinkers in the empirical world who, through their work and expository writing, are taking the place of the traditional intellectual in rendering visible the deeper meanings of our lives, redefining who and what we are. (Wired 1998) And now we are beginning to depend on computers to help us evolve new computers that let us produce things of much greater complexity. Yet we don't quite understand the process - it's getting ahead of us. We're now using programs to make much faster computers so the process can run much faster. That's what's so confusing - technologies are feeding back on themselves; we're taking off. We're at that point analogous to when single-celled organisms were turning into multicelled organisms. We are amoebas and we can't figure out what the hell this thing is that we're creating. CPS 100 8. 16
- Slides: 16