Docsity

Notes on Advanced Tree Structures - Computer Science I | COP 3502, Study notes of Computer Science

Toggle sidebar
bg1
Introduction
In the previous set of notes you were introduced to binary search trees (BSTs).
Recall that one of the problems with general BSTs is that the tree may be
unbalanced and thus skewed to the right or left. The more heavily skewed the
tree, the further in general, you will get from the logarithmic time bound on
searching in the tree. Therefore, it becomes a potentially important task to be
able to balance the search tree. We will briefly examine a global balancing
algorithm known as the DSW algorithm (named for its developer’s Day and later
improved by Stout and Warren). Algorithm’s such as the DSW algorithm
perform balancing (or rebalancing actually) on the entire tree, thus algorithm’s of
this type are known as global balancing algorithms. Global balancing
algorithms are fairly costly, particularly when the search tree is already fairly
well balanced. As an alternative, algorithms which adjust the balance of the
search tree on a local basis; that is, they do not consider the entire tree but
restrict their rebalancing to a subtree, have been developed as more efficient
techniques for such well balanced search trees. This set of notes will introduce
the AVL tree which is a search tree variant that self-balances at the local level.
Most advanced tree structures, each with particular properties regarding
balance, restricting the height growth, specifying insertion points, etc. are
geared toward searching operations in one form or another, rather than simple
data representation. We’ll start our foray into advanced tree structures with a
quick look at the DSW algorithm, and AVL trees.
Binary Search Trees
The property that turns a binary tree into a binary search tree is that for every
node x, in the tree, the values of all the items in the left subtree of x are smaller
than the item in x and the values of all the items in the right subtree of x are
larger than the item in x. Notice that this implies that every item in the tree is
part of a total ordering. Using this definition and considering the two trees
shown in Figure 1, the tree on the left is a BST while the tree on the right is not
a BST.
AVL Trees - 1
Advanced Tree Structures – AVL Trees (Day 25)
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Notes on Advanced Tree Structures - Computer Science I | COP 3502 and more Study notes Computer Science in PDF only on Docsity!

Introduction In the previous set of notes you were introduced to binary search trees (BSTs). Recall that one of the problems with general BSTs is that the tree may be unbalanced and thus skewed to the right or left. The more heavily skewed the tree, the further in general, you will get from the logarithmic time bound on searching in the tree. Therefore, it becomes a potentially important task to be able to balance the search tree. We will briefly examine a global balancing algorithm known as the DSW algorithm (named for its developer’s Day and later improved by Stout and Warren). Algorithm’s such as the DSW algorithm perform balancing (or rebalancing actually) on the entire tree, thus algorithm’s of this type are known as global balancing algorithms. Global balancing algorithms are fairly costly, particularly when the search tree is already fairly well balanced. As an alternative, algorithms which adjust the balance of the search tree on a local basis; that is, they do not consider the entire tree but restrict their rebalancing to a subtree, have been developed as more efficient techniques for such well balanced search trees. This set of notes will introduce the AVL tree which is a search tree variant that self-balances at the local level. Most advanced tree structures, each with particular properties regarding balance, restricting the height growth, specifying insertion points, etc. are geared toward searching operations in one form or another, rather than simple data representation. We’ll start our foray into advanced tree structures with a quick look at the DSW algorithm, and AVL trees. Binary Search Trees The property that turns a binary tree into a binary search tree is that for every node x , in the tree, the values of all the items in the left subtree of x are smaller than the item in x and the values of all the items in the right subtree of x are larger than the item in x. Notice that this implies that every item in the tree is part of a total ordering. Using this definition and considering the two trees shown in Figure 1, the tree on the left is a BST while the tree on the right is not a BST.

Advanced Tree Structures – AVL Trees (Day 25)

(a) (b) Figure 1 – (a) A BST, (b) Not a BST (nodes 2 and 6 are in error) Recall that inserting a new node into a BST essentially involves a search for that node which will direct you to the correct location at which it is to be inserted as a new leaf node. Note that it is not possible to insert a new internal node in a BST. Deletion of a node in a BST is trivial if the node to be deleted is a leaf node. Deletion of an internal node is also trivial if the node to be deleted has only a single child. However, if the internal node has two children, then no single step operation will be able to complete the deletion of the node. The two basic techniques for deleting a node with two children are: deletion by copying and deletion by merging. Deletion by Merging This technique makes one tree out of the two subtrees of the node which will be deleted and then attaches it to that node’s parent. The main question is how can these two subtrees be merged? The nature of the BST is that every value in the right subtree is greater than every value in the left subtree, so the best thing to do is find, within the left subtree, the node with the greatest value and make this the parent of the right subtree. Symmetrically, the node with the lowest value can be found in the right subtree and made a parent of the left subtree. The desired node is the rightmost node of the left subtree. This node can be located by traversing this subtree always taking right references until a null reference is encountered (indicating that we have reached a leaf node). This means that the node which has been located has no right child, and there is no danger of violating the property of BSTs in the original tree by setting that rightmost node’s right reference to the right subtree. [Symmetry would allow us to accomplish exactly the same effect by setting the left reference of the cc a b c e d f g i h 7 3 5 6 2 9 22 2 5 2 1 (a) (b)

the node that holds it. Deletion by copying is shown graphically in the diagrams illustrated in Figure 3. Figure 3 – Illustration of Deletion by Copying in a BST DSW Algorithm Recall that a binary tree is height-balanced or simply balanced if the difference in height of both subtrees of any node is either zero or one. A perfectly balanced tree is one in which all leaf nodes are found on one or two levels. For example, a perfectly balanced binary tree consisting of 10,000 nodes, the height of this tree will be log(10,001) = 13.289 = 14. In practical terms, this means that if 10,000 elements are stored in a perfectly balanced tree, then at most 14 nodes will need to be checked to locate a specific element. This is a substantial difference when compared to the worst case of 10,000 elements in a list! Therefore, in trees which are to be used primarily for searching, it is worth the effort to either build the tree so that it is balanced or modify the existing tree so that it is balanced. A binary tree is height-balanced (or simply balanced ) if the difference in height of both subtrees of any node in the tree is either zero or one. A tree is said to be perfectly balanced if it is balanced and all of the leaves are found on one or two levels.

The DSW algorithm, developed by Colin Day and later improved by Quentin Stout and Bette Warren, is a very elegant algorithm which requires little additional storage to effect the balancing and does not require sorting the elements in the initial tree. The basic building block for tree transformations in the DSW algorithm is the rotation. There are two types of rotations, left and right, which are symmetric to one another. The right rotation of the node Ch (for child) about its parent Par is performed according to the following algorithm: A right rotation is shown graphically in Figure 4. before rotation after rotation Figure 4 – A Right Rotation The heart of the right rotation is the third step in the algorithm, when Par , the parent of child Ch , becomes the child of Ch , i.e., when the roles of the parent and child interchange. Notice that this exchange of roles does not affect the principal property of the tree, namely, that it is still a BST. The first and second steps of the algorithm are required to ensure that after the rotation the BST property is preserved. The example in Figure 5 should clarify this property: rotateRight (Gr, Par, Ch) if Par is not the root of the tree //i.e., if Gr is not null grandparent Gr of child Ch becomes Ch’s parent by replacing Par; right subtree of Ch becomes left subtree of Ch’s parent Par; node Ch acquires Par as its right child; G r Pa r C h (^) R P Q G r Ch Pa r R P Q

Figure 6 – Creation of a Backbone for the DSW Algorithm Since the rotation requires knowledge about the parent of tmp , an additional reference must be maintained when the algorithm is implemented. In the best case, the tree is already a backbone and the while loop will execute n times and no rotation is performed. In the worst case, when the root does not have a right child, the while loop will be executed 2n-1 times and n-1 rotations will be performed, where n is the number of nodes in the tree. Thus, the run time of the first phase of the DSW algorithm is O(n). In the second phase, the backbone is transformed into a tree, but this time the tree will be perfectly balanced by having leaves only on two adjacent levels. In each pass down the backbone, every second node is rotated about its parent. One such pass decreases the size of the backbone by one-half. Only the first pass may not reach the end of the backbone. It is used to account for the difference between the number n of nodes in the current tree and the number 2 lg(n+1)-1 of nodes in the closest complete binary tree. Thus, overflowing nodes are treated separately. The core of the DSW algorithm is given below: Figure 7 illustrates this part of the DSW algorithm. createPerfectTree(n) m = 2lg(n+1)^ -1; make n-m rotations starting from the top of the backbone; while (m > 1) m = m/2; make m rotations starting from the top of the backbone;

Figure 7 – Illustration of the DSW Algorithm The example in Figure 7 starts with the backbone (a) generated in Figure 6. The first pass through the backbone to produce the backbone shown in (b). Now two passes are executed. In each backbone, the nodes to be promoted by one level by left rotations are shown as squares; their parents, about which they are rotated are shown as circles. To compute the complexity of the tree building phase, note that the number of iterations performed by the while loop equals:

 )  ( ) lg( )

lg( ) 2 lg(^ ) 1 15 7 3 1 2 1 m m 1 m 1 1 i 1 m (^11)        i   

      The number of rotations can now be given by the expression: n m  mlg( m 1 ))nlg(m 1  n lg(n 1 ) Thus, the number of rotations is O(n). Because creating a backbone also required at most O(n) rotations, the cost of global rebalancing with the DSW algorithm is optimal in terms of time because it grows linearly with n and requires a very small and fixed amount of storage. AVL Trees

tree all of the balance factor should be +1, 0, or –1. Considering the tree shown in the middle above, the balance factor of the root is +1 since the height of the right subtree is 2 and the height of the left subtree is 1 and 21 = 1. The definition of an AVL tree indicates that the minimum number of nodes in an AVL tree is defined by the recurrence equation: AVL (^) h  AVLh 1 AVLh 2  1 where AVL 0 = 0 and AVL 1 = 1 are the initial conditions. Adel’son-Vel’skii and Landis have proven that this produces the following bounds on the height of an AVL tree depending upon the number of nodes n : log(n  1 )h 1. 44 log(n 2 ) 0. 328 Therefore, the height of the tree is bounded by O(log n) and the worst case search requires O(log n) comparisons. Notice that for a perfectly balanced tree of the same height h^ ^ log(n^1 ). Therefore, the search time in the worst case in an AVL tree is 44% worse (it requires 44% more comparisons) than in the best case tree configuration. Donald Knuth has shown through empirical results that the average case number of comparisons is much closer to the best case than to the worst case and is equal to log n+0.25 for large n. This is why AVL trees are so important for searching applications, they have a logarithmic time bound on the search and are self-balancing. If the balance factor of any node in an AVL tree becomes less than –1 or greater than +1, then the tree must be balanced. Insertion An AVL tree can become unbalanced in one of four ways, two of which are symmetric to each other and thus, we need to consider only two different situations. These two cases are:

  1. The result of inserting a node in the right subtree of the right child of a node.
  2. The result of inserting a node in the left subtree of the right child. The first case is the simpler of the two and we will consider it first. Figure 8 illustrates the technique.

Figure 8 – Illustration of Insertion in an AVL Tree – Case 1 In (a) a new node is inserted somewhere in the right subtree of node Q, this causes an imbalance in the tree rooted at P since the balance factor in P is now greater than 1. The solution is to rotate node Q about its parent P which is shown in (c). Having done this the balance factor of both P and Q become 0, which is even better than the original tree! The second case, the result of inserting a new node in the left subtree of the right child, is illustrated in Figure 9. Figure 9 – Illustration of Insertion in an AVL Tree – Case 2 In (a) a new node is inserted somewhere in the left subtree of Q which creates an imbalance in the tree at node P shown in (b) and in more detail in (c). The solution to this problem is a double rotation, the first by rotating R about Q as shown in (d) and then by rotating R about P as shown in (e). Both of the cases illustrated use a stand-alone tree to illustrate the technique of the rotation, however, the tree rooted at P can be part of a larger AVL tree. If P itself is the child of some node (it is not the root of the entire tree), the question arises, will additional work be required to adjust the balance of P’s

initial AVL tree – shown with balance factors

  1. An insertion occurs in the left subtree of the right child of node 26 (case 2)
  2. The subtree rooted at node 20 must be singly rotated to restore balance. AVL Trees - **13 3 0 2 0 5 0 1 0 2 6 4 0 7 0 2 3 2 8 4 5 9 0 2 7 0

2 0 0 + 1

1

1 0 -1 0 0 0 3 0 2 6 5 0 2 0 2 8 4 0 7 0 1 2 2 4 9**

final AVL tree showing data values final AVL tree showing balance factors Example 2

  1. An initial AVL tree AVL Trees - **14 0 0 0 0 -1 + 1

1 0 0 0 0 0 3 0 2 0 5 0 1 0 2 6 4 0 7 0 2 2 4 9**

  1. The subtree rooted at node 20 must be singly rotated to restore balance. final AVL tree showing data values final AVL tree showing balance factors It is possible that the insertion of a new node into an AVL tree will not require a rotation as the new tree may remain balanced. If the balance factors from the newly inserted node up to the root of the tree are all zero, the balance factors will need to be updated from the insertion point up to the root of the tree, but no 3 **0 2 6 5 0 2 0 2 8 4 0 7 0 1 0 2 9 4 5 9 0 2 3 0 0 0 0 + 1

1

1 0 0 0 0 0**

rotation will need to be performed. This situation is illustrated in the following example: Initial AVL tree Nodes along the indicated path must all have balance factors reset **0 0 0

1 0 + 1

1 0 0 0 0 0 0 0 0

1 0 + 1

1 0 0 0 0 0 0**  **1

1 0**

Figure 10 – Deletion in an AVL Tree The first case of deletion is represented in (a) which after the deletion (which occurs in the left subtree of the right child of P ) turns into the tree in (b). The tree is rebalanced by rotating Q about P which gives the final tree (c) for the first case. The second case of deletion is represented in (d) in which node P has a balance factor of +1, and its right subtree Q has a balance factor equal to 0. After the deletion of a node in the left subtree of P , shown in (e), the tree is rebalanced using exactly the same rotation as in the first case to produce the tree shown in (f). Notice that cases 1 and 2 can be processed together in an implementation after checking that the balance factor of Q is +1 or 0.

When Q is –1, the other two cases for deletion occur which are both more complicated than the first two. In the third case, the left subtree R of Q has a balance factor equal to –1 as shown in (g). To rebalance the tree, first R is rotated about Q (h) and then about P (i). The fourth case differs from the third case only in that R ’s balance factor is +1, as in (j), in which case the same two rotations are performed in order to restore the balance factor of P (shown in (k) and (l)). As before, cases three and four can be processed together based only upon a check of the balance factor associated with node R. Final Comments On AVL Trees Insertions and deletions in an AVL tree require at most 1.44 log(n+2) comparisons. Insertion can require either one single rotation or one double rotation, and deletion can require 1.44 log(n+2) rotations, in the worst case. However, as mentioned earlier, the average case requires log(n) + 0. comparisons, which reduces the number of rotations in the case of deletions to this number. In the average case, insertion may lead to one single/one double rotation. Empirical results, based primarily upon simulations, have indicated that deletions in 78% of the cases will not require a rebalancing at all! On the other hand, only 53% of the insertions do not force the tree out of balance. Therefore, the more time-consuming deletion operation occurs less frequently than the insertion operation, which does not unduly limit the efficiency of rebalancing AVL trees. AVL trees can be extended by allowing the differences in heights, , of subtrees to be greater than 1. For example, you can allow subtrees to become more and more unbalanced by allowing a greater height differential between the left and right subtrees. Not unexpectedly, the worst-case height increases as  increases. Again empirical results indicate the following trend: ^        ^  215 n 113 if 3 h 181 n^071 if^2

. log( ). . log( ). As the experimental evidence indicates, the average number of visited nodes increases by one-half in comparison to pure AVL trees ( = 1), but the amount of restructuring required can be decreased by a factor of 10!