850 likes | 1.02k Views
Advanced Trees Part II. Briana B. Morrison Adapted from Alan Eugenio & William J. Collins. Topics. AVL Trees Part III 2-3-4 Search Trees Red Black Trees. AVL Tree Definition. AVL trees are balanced.
E N D
Advanced TreesPart II Briana B. Morrison Adapted from Alan Eugenio & William J. Collins
Topics • AVL Trees • Part III • 2-3-4 Search Trees • Red Black Trees Advanced Trees (Part II)
AVL Tree Definition • AVL trees are balanced. • An AVL Tree is a binary search tree such that for every internal node v of T, the heights of the children of v can differ by at most 1. An example of an AVL tree where the heights are shown next to the nodes: Advanced Trees (Part II)
Balance Factor • The balance factor is defined as: • The height of the left subtree minus the height of the right subtree • The tree is balanced if the absolute value of the balance factor is <=1 │ ht(TL) – ht(TR) │ <= 1 Advanced Trees (Part II)
20 HEIGHT OF LEFT SUBTREE = ? HEIGHT OF RIGHT SUBTREE = ? Advanced Trees (Part II)
NOPE! THE HEIGHT OF THE LEFT SUBTREE IS 1 AND THE HEIGHT OF THE RIGHT SUBTREE IS –1. Advanced Trees (Part II)
NOPE: THE LEFT AND RIGHT SUBTREES ARE NOT AVL TREES, SO THE TREE IS NOT AN AVL TREE. Advanced Trees (Part II)
NOPE! THE HEIGHT OF THE LEFT SUBTREE IS 2 AND THE HEIGHT OF THE RIGHT SUBTREE IS 0. Advanced Trees (Part II)
n(2) 3 n(1) 4 Height of an AVL Tree • Fact: The height of an AVL tree storing n keys is O(log n). • Proof: Let us bound n(h): the minimum number of internal nodes of an AVL tree of height h. • We easily see that n(1) = 1 and n(2) = 2 • For n > 2, an AVL tree of height h contains the root node, one AVL subtree of height n-1 and another of height n-2. • That is, n(h) = 1 + n(h-1) + n(h-2) • Knowing n(h-1) > n(h-2), we get n(h) > 2n(h-2). So n(h) > 2n(h-2), n(h) > 4n(h-4), n(h) > 8n(n-6), … (by induction), n(h) > 2in(h-2i) • Solving the base case we get: n(h) > 2 h/2-1 • Taking logarithms: h < 2log n(h) +2 • Thus the height of an AVL tree is O(log n) Advanced Trees (Part II)
ITEMS NOT IN THE SUBTREE OF THE ITEM ROTATED ABOUT ARE UNAFFECTED BY THE ROTATION. • A ROTATION TAKES CONSTANT TIME. • BEFORE AND AFTER A ROTATION, THE TREE IS STILL A BINARY SEARCH TREE. • THE CODE FOR A LEFT ROTATION IS SYMMETRIC TO THE CODE FOR A RIGHT ROTATION: SIMPLY SWAP “left” AND “right”. Advanced Trees (Part II)
Now let’s look at some examples of inserting into an AVL tree to get an idea of how all this rotation stuff works: Advanced Trees (Part II)
Example – Insert numbers 1-7 into AVL Advanced Trees (Part II)