Tutorial AVL TREES

Total Page:16

File Type:pdf, Size:1020Kb

Tutorial AVL TREES 1 Tutorial AVL TREES Binary search trees are designed for efficient access to data. In some cases, however, a binary search tree is degenerate or "almost degenerate" with most of the n elements descending as a linked list in one of the subtrees of a node. The search efficiency of the tree becomes O(n). A complete binary tree is the other extreme. Nodes are uniformly distributed among left and right subtrees allowing the structure to store n elements in a tree of minimum height. The longest path is log2 n +1 and the search efficiency is O(log2 n). Intuitively, a degenerate binary tree is very "unbalanced" in the sense that all of the nodes lie in one of the subtrees of the root. On the other hand, a complete binary tree is "balanced" in the sense that nodes are equitably distributed between the two subtrees of a node. Ideally, all binary search trees would be complete trees. This is not possible with random data. The problem is the insert() and erase() algorithms that add or remove an element without any follow-up analysis to determine how the action affects the overall balance of the tree. To address this problem, researchers Adelson, Velskii and Landis defined the concept of height-balance for a node and developed new search tree insert and erase algorithms that would reorder the elements to maintain height-balance. The binary search trees with these new algorithms are called AVL trees after their creators. Besides the usual search-ordering of nodes it the tree, an AVL tree is height- balanced. By this we mean that for each node in the tree, the difference in height (depth) of its two subtrees is at most 1. Figure 1 displays equivalent binary search and AVL trees that store array data. The first example uses array arrA, whose elements are in ascending order while the second example uses array arrB, whose elements are in random order. arrA[5] = {1,2,3,4,5} arrB[8] = {20,30,80,40,10,60,50,70} Binary Search Tree AVL Tree 1 2 2 1 4 5 3 3 4 arrA = {1, 2, 3, 4, 5} 5 Binary Search Tree AVL Tree 20 30 10 30 20 80 80 10 40 80 40 60 50 70 50 70 arrB = {20,30,80,40,10,60,50,70} FIGURE 1 Equivalent Binary Search and AVL Trees 2 The binary search tree for array arrA has a height of 5, whereas the AVL tree has a height of 2. In general, the height of an AVL tree never exceeds O(log2 n). This fact makes an AVL tree an efficient search container when rapid access to elements is demanded. 1 AVL Tree Nodes AVL trees are modeled after binary search trees. The operations are identical although the action of the AVL tree insert() and erase() functions are quite different since they must preserve the balance feature of the tree. To maintain a measure of balance, we define an avlTreeNode object with the integer balanceFactor as an additional field. left nodeValue balanceFactor right avlTreeNode The value of the field is the difference between the height of the right and left subtrees of the node. balanceFactor = height(right-subtree) - height(left-subtree) If balanceFactor is negative, the node is "heavy on the left" since the height of the left subtree is greater than the height of the right subtree. With balanceFactor positive, the node is "heavy on the right." A balanced node has balanceFactor = 0. An AVL tree is a binary search tree in which the balance-factor of each node is in the range -1 to 1. Figure 2 describes three AVL trees with tags -1, 0, or +1 on each node to indicate its balance-factor (relative height of the left and right subtrees). -1: height of the left subtree is one greater than the right subtree. 0: height of the left and right subtrees are equal. +1: height of the right subtree is one greater than the left subtree. (a) 10 (b) 50 (c) 50 (+1) (-1) (+1) 20 20 60 20 60 (0) (+1) (0) (0) (+1) 40 80 (0) (0) FIGURE 2 AVL trees with balance-factor of each node in parentheses The avlTreeNode class is similar to the tnode class for binary search trees. Four public data members include the data value, the left and right pointers, and the balance factor. The constructor is used to create a node for an AVL tree and initialize the data members. 3 DECLARATION: avlTreeNode CLASS // declares a tree node object for a binary tree template <typename T> class avlTreeNode { public: // data in the node T nodeValue; // pointers to the left and right children of the node avlTreeNode<T> *left; avlTreeNode<T> *right; int balanceFactor; // CONSTRUCTOR avlTreeNode (const T& item, avlTreeNode<T> *lptr = NULL, avlTreeNode<T> *rptr = NULL, int bal = 0): nodeValue(item), left(lptr), right(rptr), balanceFactor(bal) {} }; 2 The avlTree Class The avlTree class with the same programmer-interface used by the stree. The class has both constant and non- constant iterators, which can be used to scan the list of elements. A non-constant version is supplied so that a program can use the deference operator * to update the data value of a node. This feature can be used when the AVL trees stores records with a key and other data values and the update modifies only the data values. An attempt to update the key could destroy the structure of the tree. Like BinSTree iterators, AVL iterators are forward iterators but with an important limitation. Since a tree may need to be rebalanced when an item is added or removed , the insert() and erase() operations invalidate all iterators. To be used again, the iterators must be reset to the start of the list with begin(). The following is a declaration of the programmer-interface for the avlTree class. We implement only the insert() method and do not discuss the erase() methods. The method clear() is added to remove all of the nodes in the tree. In the stree class, clear is executed by calling erase() with the iterator range [begin(), end()). The memory management functions are not included We will expand the declaration to include the private member functions when we discuss the implementation of the class. DECLARATION: avlTree CLASS (Programmer-Interface template <typename T> class avlTree { // CONSTRUCTORS, DESTRUCTOR, ASSIGNMENT // constructor. initialize root to NULL and size to 0 avlTree(); // constructor. insert n elements from range of T* pointers 4 avlTree(T *first, T *last); // search for item. if found, return an iterator pointing // at it in the tree; otherwise, return end() iterator find(const T& item); // search for item. if found, return an iterator pointing // at it in the tree; otherwise, return end() const_iterator find(const T& item) const; // indicate whether the tree is empty int empty() const; // return the number of data items in the tree int size() const; // give a vertical display of the tree . void displayTree(int maxCharacters) const; // insert item into the tree //pair<iterator, bool> insert(const T& item); // insert a new node using the basic List operation and format pair<iterator, bool> insert(const T& item); // delete all the nodes in the tree void clear(); // constant versions iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; }; The function displayTree() is similar to displayTree() in the stree class. It includes both the label and the balance-factor for each node in the format <label> : <balanceFactor> EXAMPLE 1 The example illustrates the use of the avlTree operations. 1. Declare an avlTree object avltreeA that stores integers and an object avlTreeB that stores real numbers with initial values from array arrB. // avlTreeA is empty tree of integers avlTree<int> avlTreeA; // avlTreeB is a tree of reals with 6 initial values double arrB[6] = {2.8, 3.9, -2.0, 4.9, 8.6, -12.8}; avlTree<double> avltreeB(arrB, arrB+6); 2. A loop initializes avlTreeA with integers 0 to 9. The tree is displayed with displayTree() for (i = 1; i < 10; i++) 5 avlTreeA.insert(i); avlTreeA.displayTree(2); 3:1 1:0 7:0 0:0 2:0 5:0 8:1 4:0 6:0 9:0 3. Determine whether 8.6 and 1.6 are elements in avlTreeB. avlTree<double>::iterator dblIter; if ((dblIter = avlTreeB.find(8.6)) != avlTreeB.end()) cout << "Element " << *dblIter << " is an element in AVL tree" << endl; if ((dblIter = avlTreeB.find(1.6)) == avlTreeB.end()) cout << "Element 1.6 is not an element in AVL tree" << endl; Solution: Element 8.6 is an element in AVL tree Element 1.6 is not an element in AVL tree 3 Application: Updating Character Counts An AVL tree is most effective in situations where the data statically resides in the tree and the application primarily searches for items and updates their value. A simple example declares objects of type charCount that contain a character and its frequency (count) as data members. The class has a constructor that with a char argument that initializes the data member and sets the count to 1. The class also provides overloaded versions of the comparison operators < and == along with overloaded version of the << operator. The comparison operators allow charCount to be used as the template type for avlTree objects and their implementation compares only at the char value of the operands. The << operator outputs the character and its count in the form <char>(<count>). In the example, we count the number of occurrences of the letters 'a' to 'z' in the 25000+ word dictionary "words.dat".
Recommended publications
  • Lecture 26 Fall 2019 Instructors: B&S Administrative Details
    CSCI 136 Data Structures & Advanced Programming Lecture 26 Fall 2019 Instructors: B&S Administrative Details • Lab 9: Super Lexicon is online • Partners are permitted this week! • Please fill out the form by tonight at midnight • Lab 6 back 2 2 Today • Lab 9 • Efficient Binary search trees (Ch 14) • AVL Trees • Height is O(log n), so all operations are O(log n) • Red-Black Trees • Different height-balancing idea: height is O(log n) • All operations are O(log n) 3 2 Implementing the Lexicon as a trie There are several different data structures you could use to implement a lexicon— a sorted array, a linked list, a binary search tree, a hashtable, and many others. Each of these offers tradeoffs between the speed of word and prefix lookup, amount of memory required to store the data structure, the ease of writing and debugging the code, performance of add/remove, and so on. The implementation we will use is a special kind of tree called a trie (pronounced "try"), designed for just this purpose. A trie is a letter-tree that efficiently stores strings. A node in a trie represents a letter. A path through the trie traces out a sequence ofLab letters that9 represent : Lexicon a prefix or word in the lexicon. Instead of just two children as in a binary tree, each trie node has potentially 26 child pointers (one for each letter of the alphabet). Whereas searching a binary search tree eliminates half the words with a left or right turn, a search in a trie follows the child pointer for the next letter, which narrows the search• Goal: to just words Build starting a datawith that structure letter.
    [Show full text]
  • Search Trees
    Lecture III Page 1 “Trees are the earth’s endless effort to speak to the listening heaven.” – Rabindranath Tagore, Fireflies, 1928 Alice was walking beside the White Knight in Looking Glass Land. ”You are sad.” the Knight said in an anxious tone: ”let me sing you a song to comfort you.” ”Is it very long?” Alice asked, for she had heard a good deal of poetry that day. ”It’s long.” said the Knight, ”but it’s very, very beautiful. Everybody that hears me sing it - either it brings tears to their eyes, or else -” ”Or else what?” said Alice, for the Knight had made a sudden pause. ”Or else it doesn’t, you know. The name of the song is called ’Haddocks’ Eyes.’” ”Oh, that’s the name of the song, is it?” Alice said, trying to feel interested. ”No, you don’t understand,” the Knight said, looking a little vexed. ”That’s what the name is called. The name really is ’The Aged, Aged Man.’” ”Then I ought to have said ’That’s what the song is called’?” Alice corrected herself. ”No you oughtn’t: that’s another thing. The song is called ’Ways and Means’ but that’s only what it’s called, you know!” ”Well, what is the song then?” said Alice, who was by this time completely bewildered. ”I was coming to that,” the Knight said. ”The song really is ’A-sitting On a Gate’: and the tune’s my own invention.” So saying, he stopped his horse and let the reins fall on its neck: then slowly beating time with one hand, and with a faint smile lighting up his gentle, foolish face, he began..
    [Show full text]
  • Comparison of Dictionary Data Structures
    A Comparison of Dictionary Implementations Mark P Neyer April 10, 2009 1 Introduction A common problem in computer science is the representation of a mapping between two sets. A mapping f : A ! B is a function taking as input a member a 2 A, and returning b, an element of B. A mapping is also sometimes referred to as a dictionary, because dictionaries map words to their definitions. Knuth [?] explores the map / dictionary problem in Volume 3, Chapter 6 of his book The Art of Computer Programming. He calls it the problem of 'searching,' and presents several solutions. This paper explores implementations of several different solutions to the map / dictionary problem: hash tables, Red-Black Trees, AVL Trees, and Skip Lists. This paper is inspired by the author's experience in industry, where a dictionary structure was often needed, but the natural C# hash table-implemented dictionary was taking up too much space in memory. The goal of this paper is to determine what data structure gives the best performance, in terms of both memory and processing time. AVL and Red-Black Trees were chosen because Pfaff [?] has shown that they are the ideal balanced trees to use. Pfaff did not compare hash tables, however. Also considered for this project were Splay Trees [?]. 2 Background 2.1 The Dictionary Problem A dictionary is a mapping between two sets of items, K, and V . It must support the following operations: 1. Insert an item v for a given key k. If key k already exists in the dictionary, its item is updated to be v.
    [Show full text]
  • AVL Tree, Bayer Tree, Heap Summary of the Previous Lecture
    DATA STRUCTURES AND ALGORITHMS Hierarchical data structures: AVL tree, Bayer tree, Heap Summary of the previous lecture • TREE is hierarchical (non linear) data structure • Binary trees • Definitions • Full tree, complete tree • Enumeration ( preorder, inorder, postorder ) • Binary search tree (BST) AVL tree The AVL tree (named for its inventors Adelson-Velskii and Landis published in their paper "An algorithm for the organization of information“ in 1962) should be viewed as a BST with the following additional property: - For every node, the heights of its left and right subtrees differ by at most 1. Difference of the subtrees height is named balanced factor. A node with balance factor 1, 0, or -1 is considered balanced. As long as the tree maintains this property, if the tree contains n nodes, then it has a depth of at most log2n. As a result, search for any node will cost log2n, and if the updates can be done in time proportional to the depth of the node inserted or deleted, then updates will also cost log2n, even in the worst case. AVL tree AVL tree Not AVL tree Realization of AVL tree element struct AVLnode { int data; AVLnode* left; AVLnode* right; int factor; // balance factor } Adding a new node Insert operation violates the AVL tree balance property. Prior to the insert operation, all nodes of the tree are balanced (i.e., the depths of the left and right subtrees for every node differ by at most one). After inserting the node with value 5, the nodes with values 7 and 24 are no longer balanced.
    [Show full text]
  • AVL Insertion, Deletion Other Trees and Their Representations
    AVL Insertion, Deletion Other Trees and their representations Due now: ◦ OO Queens (One submission for both partners is sufficient) Due at the beginning of Day 18: ◦ WA8 ◦ Sliding Blocks Milestone 1 Thursday: Convocation schedule ◦ Section 01: 8:50-10:15 AM ◦ Section 02: 10:20-11:00 AM, 12:35-1:15 PM ◦ Convocation speaker Risk Analysis Pioneer John D. Graham The promise and perils of science and technology regulations 11:10 a.m. to 12:15 p.m. in Hatfield Hall. ◦ Part of Thursday's class time will be time for you to work with your partner on SlidingBlocks Due at the beginning of Day 19 : WA9 Due at the beginning of Day 21 : ◦ Sliding Blocks Final submission Non-attacking Queens Solution Insertions and Deletions in AVL trees Other Search Trees BSTWithRank WA8 Tree properties Height-balanced Trees SlidingBlocks CanAttack( ) toString( ) findNext( ) public boolean canAttack(int row, int col) { int columnDifference = col - column ; return currentRow == row || // same row currentRow == row + columnDifference || // same "down" diagonal currentRow == row - columnDifference || // same "up" diagonal neighbor .canAttack(row, col); // If I can't attack it, maybe // one of my neighbors can. } @Override public String toString() { return neighbor .toString() + " " + currentRow ; } public boolean findNext() { if (currentRow == MAXROWS ) { // no place to go until neighbors move. if (! neighbor .findNext()) return false ; // Neighbor can't move, so I can't either. currentRow = 0; // about to be bumped up to 1. } currentRow ++; return testOrAdvance(); // See if this new position works. } You did not have to write this one: // If this is a legal row for me, say so. // If not, try the next row.
    [Show full text]
  • Ch04 Balanced Search Trees
    Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015 Ch04 Balanced Search Trees 6 v 3 8 z 4 1 1 Why care about advanced implementations? Same entries, different insertion sequence: Not good! Would like to keep tree balanced. 2 1 Balanced binary tree The disadvantage of a binary search tree is that its height can be as large as N-1 This means that the time needed to perform insertion and deletion and many other operations can be O(N) in the worst case We want a tree with small height A binary tree with N node has height at least (log N) Thus, our goal is to keep the height of a binary search tree O(log N) Such trees are called balanced binary search trees. Examples are AVL tree, and red-black tree. 3 Approaches to balancing trees Don't balance May end up with some nodes very deep Strict balance The tree must always be balanced perfectly Pretty good balance Only allow a little out of balance Adjust on access Self-adjusting 4 4 2 Balancing Search Trees Many algorithms exist for keeping search trees balanced Adelson-Velskii and Landis (AVL) trees (height-balanced trees) Red-black trees (black nodes balanced trees) Splay trees and other self-adjusting trees B-trees and other multiway search trees 5 5 Perfect Balance Want a complete tree after every operation Each level of the tree is full except possibly in the bottom right This is expensive For example, insert 2 and then rebuild as a complete tree 6 5 Insert 2 & 4 9 complete tree 2 8 1 5 8 1 4 6 9 6 6 3 AVL - Good but not Perfect Balance AVL trees are height-balanced binary search trees Balance factor of a node height(left subtree) - height(right subtree) An AVL tree has balance factor calculated at every node For every node, heights of left and right subtree can differ by no more than 1 Store current heights in each node 7 7 Height of an AVL Tree N(h) = minimum number of nodes in an AVL tree of height h.
    [Show full text]
  • Balanced Binary Search Trees – AVL Trees, 2-3 Trees, B-Trees
    Balanced binary search trees – AVL trees, 2‐3 trees, B‐trees Professor Clark F. Olson (with edits by Carol Zander) AVL trees One potential problem with an ordinary binary search tree is that it can have a height that is O(n), where n is the number of items stored in the tree. This occurs when the items are inserted in (nearly) sorted order. We can fix this problem if we can enforce that the tree remains balanced while still inserting and deleting items in O(log n) time. The first (and simplest) data structure to be discovered for which this could be achieved is the AVL tree, which is names after the two Russians who discovered them, Georgy Adelson‐Velskii and Yevgeniy Landis. It takes longer (on average) to insert and delete in an AVL tree, since the tree must remain balanced, but it is faster (on average) to retrieve. An AVL tree must have the following properties: • It is a binary search tree. • For each node in the tree, the height of the left subtree and the height of the right subtree differ by at most one (the balance property). The height of each node is stored in the node to facilitate determining whether this is the case. The height of an AVL tree is logarithmic in the number of nodes. This allows insert/delete/retrieve to all be performed in O(log n) time. Here is an example of an AVL tree: 18 3 37 2 11 25 40 1 8 13 42 6 10 15 Inserting 0 or 5 or 16 or 43 would result in an unbalanced tree.
    [Show full text]
  • Performance Analysis of Bsts in System Software∗
    Performance Analysis of BSTs in System Software∗ Ben Pfaff Stanford University Department of Computer Science [email protected] Abstract agement and networking, and the third analyzes a part of a source code cross-referencing tool. In each Binary search tree (BST) based data structures, such case, some test workloads are drawn from real-world as AVL trees, red-black trees, and splay trees, are of- situations, and some reflect worst- and best-case in- ten used in system software, such as operating system put order for BSTs. kernels. Choosing the right kind of tree can impact performance significantly, but the literature offers few empirical studies for guidance. We compare 20 BST We compare four variants on the BST data struc- variants using three experiments in real-world scenar- ture: unbalanced BSTs, AVL trees, red-black trees, ios with real and artificial workloads. The results in- and splay trees. The results show that each should be dicate that when input is expected to be randomly or- preferred in a different situation. Unbalanced BSTs dered with occasional runs of sorted order, red-black are best when randomly ordered input can be relied trees are preferred; when insertions often occur in upon; if random ordering is the norm but occasional sorted order, AVL trees excel for later random access, runs of sorted order are expected, then red-black trees whereas splay trees perform best for later sequential should be chosen. On the other hand, if insertions or clustered access. For node representations, use of often occur in a sorted order, AVL trees excel when parent pointers is shown to be the fastest choice, with later accesses tend to be random, and splay trees per- threaded nodes a close second choice that saves mem- form best when later accesses are sequential or clus- ory; nodes without parent pointers or threads suffer tered.
    [Show full text]
  • Lecture 13: AVL Trees and Binary Heaps
    Data Structures Brett Bernstein Lecture 13: AVL Trees and Binary Heaps Review Exercises 1.( ??) Interview question: Given an array show how to shue it randomly so that any possible reordering is equally likely. static void shue(int[] arr) 2. Write a function that given the root of a binary search tree returns the node with the largest value. public static BSTNode<Integer> getLargest(BSTNode<Integer> root) 3. Explain how you would use a binary search tree to implement the Map ADT. We have included it below to remind you. Map.java //Stores a mapping of keys to values public interface Map<K,V> { //Adds key to the map with the associated value. If key already //exists, the associated value is replaced. void put(K key, V value); //Gets the value for the given key, or null if it isn't found. V get(K key); //Returns true if the key is in the map, or false otherwise. boolean containsKey(K key); //Removes the key from the map void remove(K key); //Number of keys in the map int size(); } What requirements must be placed on the Map? 4. Consider the following binary search tree. 10 5 15 1 12 18 16 17 1 Perform the following operations in order. (a) Remove 15. (b) Remove 10. (c) Add 13. (d) Add 8. 5. Suppose we begin with an empty BST. What order of add operations will yield the tallest possible tree? Review Solutions 1. One method (popular in programs like Excel) is to generate a random double corre- sponding to each element of the array, and then sort the array by the corresponding doubles.
    [Show full text]
  • CS302ES Regulations
    DATA STRUCTURES Subject Code: CS302ES Regulations : R18 - JNTUH Class: II Year B.Tech CSE I Semester Department of Computer Science and Engineering Bharat Institute of Engineering and Technology Ibrahimpatnam-501510,Hyderabad DATA STRUCTURES [CS302ES] COURSE PLANNER I. CourseOverview: This course introduces the core principles and techniques for Data structures. Students will gain experience in how to keep a data in an ordered fashion in the computer. Students can improve their programming skills using Data Structures Concepts through C. II. Prerequisite: A course on “Programming for Problem Solving”. III. CourseObjective: S. No Objective 1 Exploring basic data structures such as stacks and queues. 2 Introduces a variety of data structures such as hash tables, search trees, tries, heaps, graphs 3 Introduces sorting and pattern matching algorithms IV. CourseOutcome: Knowledge Course CO. Course Outcomes (CO) Level No. (Blooms Level) CO1 Ability to select the data structures that efficiently L4:Analysis model the information in a problem. CO2 Ability to assess efficiency trade-offs among different data structure implementations or L4:Analysis combinations. L5: Synthesis CO3 Implement and know the application of algorithms for sorting and pattern matching. Data Structures Data Design programs using a variety of data structures, CO4 including hash tables, binary and general tree L6:Create structures, search trees, tries, heaps, graphs, and AVL-trees. V. How program outcomes areassessed: Program Outcomes (PO) Level Proficiency assessed by PO1 Engineeering knowledge: Apply the knowledge of 2.5 Assignments, Mathematics, science, engineering fundamentals and Tutorials, Mock an engineering specialization to the solution of II B Tech I SEM CSE Page 45 complex engineering problems.
    [Show full text]
  • Data Structures Lecture 11
    Fall 2021 Fang Yu Software Security Lab. Data Structures Dept. Management Information Systems, National Chengchi University Lecture 11 Search Trees Binary Search Trees, AVL trees, and Splay Trees 3 Binary Search Trees ¡ A binary search tree is a binary tree storing keys (or key-value ¡ An inorder traversal of a binary entries) at its internal nodes and search trees visits the keys in an satisfying the following increasing order property: ¡ Let u, v, and w be three nodes such that u is in the left subtree of v and w is in the right subtree of v. 6 We have key(u) ≤ key(v) ≤ key(w) 2 9 ¡ External nodes do not store items 1 4 8 4 Search Algorithm TreeSearch(k, v) ¡ To search for a key k, we trace if T.isExternal (v) a downward path starting at the return v root if k < key(v) return TreeSearch(k, T.left(v)) ¡ The next node visited depends else if k key(v) on the comparison of k with the = return v key of the current node else { k > key(v) } ¡ If we reach a leaf, the key is return TreeSearch(k, T.right(v)) not found < 6 ¡ Example: get(4): 2 9 > ¡ Call TreeSearch(4,root) 1 4 = 8 ¡ The algorithms for floorEntry and ceilingEntry are similar 5 Insertion 6 ¡ To perform operation put(k, o), < we search for key k (using 2 9 > TreeSearch) 1 4 8 > ¡ Assume k is not already in the tree, and let w be the leaf w reached by the search 6 ¡ We insert k at node w and expand w into an internal node 2 9 ¡ Example: insert 5 1 4 8 w 5 6 Deletion 6 ¡ To perform operation remove(k), < we search for key k 2 9 > ¡ Assume key k is in the tree, and 1 4 v 8 let v be
    [Show full text]
  • Balanced Search Trees
    Balanced Search Trees ● Binary search trees keep keys ordered, with efficient lookup ➤ Insert, Delete, Find, all are O(log n) in average case ➤ Worst case is bad ➤ Compared to hashing? Advantages? ● Balanced trees are guaranteed O(log n) in the worst case ➤ Fundamental operation is a rotation: keep tree roughly balanced ➤ AVL tree was the first one, still studied since simple conceptually ➤ Red-Black tree uses rotations, harder to code, better in practice ➤ B-trees are used when data is stored on disk rather than in memory CPS 100 12.1 Rotations and balanced trees ● Height-balanced trees ➤ For every node, left and right subtree heights differ by at most 1 ➤ After insertion/deletion need to rebalance Are these trees height- ➤ Every operation leaves tree in balanced? a balanced state: invariant property of tree ● Find deepest node that’s unbalanced ➤ On path from root to insert/deleted node ➤ Rebalance at this unbalanced point only CPS 100 12.2 Rotation to rebalance N ● When a node N is unbalanced N height differs by 2 (must be more than one) C A ➤ Change N->left->left • doLeft A B B C ➤ Change N->left->right • doLeftRight Tree * doLeft(Tree * root) ➤ Change N->right->left { • doRightLeft Tree * newRoot = root->left; ➤ Change N->right->right root->left = newRoot->right; • doRight newRoot->right = root; ● First/last cases are symmetric return newRoot; ● Middle cases require two rotation } ➤ First of the two puts tree into doLeft or doRight CPS 100 12.3 Rotation to rebalance ????? N ● Suppose we add a new node in right N subtree of left child
    [Show full text]