









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










COP 3503 – Computer Science II – CLASS NOTES - DAY # The previous day’s notes introduced the special case of the binary tree known as the binary search tree (BST). As mentioned before general search trees are called M-way search trees and are beyond the scope of this course. A binary search tree is a special case of an m-way search tree defined as follows: Insertion into a BST In the previous day’s notes we saw that insertion into a BST is a straight forward procedure which basically involves searching for the value to be inserted, knowing that it is presently not in the tree. The search will always be unsuccessful and will terminate on a leaf node (actual termination will occur on the null child reference at this leaf node). Once the “dead-end” is found, the insertion is straightforward. Deletion in a BST The complexity of the deletion operation is dependent upon the position of the node to be deleted in the tree. It is a far more difficult operation to delete a node which is the root of two non-null subtrees than it is to delete a leaf node. The complexity of the deletion operation is proportional to the number of children of the node to be deleted.
A BST with a leaf node The BST with the leaf node marked for deletion deleted. A BST remains
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 leftmost node of the right subtree to the left subtree.] This operation is depicted graphically in the diagram below. The algorithm for effecting a deletion in a BST via merging is given below. public void deletebyMerging ( int element) { IBSTNode tmp, node, p = root, prev = null; while (p != null && p.key != element) {//find the node with key = element prev = p; if (p.key < element) p = p.right;
else p = p.left; } node = p; if (p != null && p.key == element) { if (node.right == null) //node has no right child node = node.left; else if (node.left == null) //node has no left child node = node.right; else { //prepare for merging tmp = node.left; //move left while (tmp.right != null) //now go to the right as far as possible tmp = tmp.right; tmp.right = node.right; //set link between rightmost node of the left subtree // and the right subtree node = node.left; } if (p == root) root = node; else if (prev.left == p) prev.left = node; else prev.right = node; }//end if else if (root != null) System.out.println(“key “ + element + “ is not in the tree”); else System.out.println(“the tree is empty”); } Deletion via Merging
resulting tree has decreased height node 15 to be deleted It isn’t that the algorithm is inefficient, but it certainly is not perfect. There is however a need for an algorithm that does not give the resulting tree the chance to increase in height through deletion. The second technique, deletion via copying, provides us with this solution. Deletion via copying Deletion via copying was proposed by Thomas Hibbard and Donald Knuth. If the node has two children, it can be reduced to one of two simple cases: The node is a leaf or the node has only one nonempty child. This can be done by replacing the key being deleted with its immediate predecessor (or successor). As we mentioned in the previous technique of deleting via merging, a key’s predecessor is the key in the rightmost node in the left subtree (via symmetry, its immediate successor is the key in the leftmost node in the right subtree). First, the predecessor has to be located. This is again done by moving one step to the left by first reaching the root of the node’s left subtree and then moving as far to the right as possible. Next, the key of the located node replaces the key to be deleted. At this point is where one of the two simple cases comes into play. If the rightmost node is a leaf, the first case applies; however, if it has one child the second case will apply. In this way, deletion via copying removes a key k 1 by overwriting it with another key k 2 and then removing the node that holds k 2 , whereas deletion by merging consisted of removing a key k 1 along with the node that holds it. Deletion by copying is shown graphically in the diagrams below as a step by step process. 1 0 5 4 7 3 0 2 0 4 0
This deletion via copying does not increase the height of the tree, but it is not without its own problems. The problem arises if the algorithm is applies many times along with insertions into the BST. This algorithm is asymmetric; it always deletes the node of the immediate predecessor of information in node. This has the effect of possibly reducing the height of the left subtree (it might not change the height). However, the right subtree is unaffected by these changes. Therefore, the right subtree of node can grow after subsequent insertions, and if the information in node is again deleted, the height of the right tree will remain the same. After many insertions and deletions, the entire tree becomes right skewed (unbalanced favoring the right side). To prevent this problem from occurring, a simple improvement to the Hibbard/Knuth algorithm will make the algorithm symmetric. In the improved algorithm, the predecessor information which is to be deleted will alternate between left and right subtrees with each deletion operation. In this fashion the first deletion will delete the predecessor information in a node in the left subtree and the next deletion will delete the successor in the right subtree. Day 17 - 8 public void deleteByCopying( int element) { IBSTNode node, p = root, prev = null; while (p != null && !p.key.equals(element) ) {//find node p with value element prev = p; if (p.key.isLessThan(element)) p = p.right; else p = p.left; } node = p; if (p != null && p.key.equals(element)) { if (node.right == null) //node has no right child node = node.left; else if (node.left == null) //node has no left child node = node.right; else { //node has two children IBSTNode tmp = node.left; IBSTNode previous = node; while (tmp.right != null) { previous = tmp; tmp = tmp.right; } node.key = tmp.key; //overwrite reference, i.e., the copy if (previous == node) previous.left = tmp.left; //node’s left child’s right subtree is null else previous.right = tmp.left; } if (p == root) root = node; else if (prev.left == p) prev.left = node; else prev.right = node; } else if (root != null) System.out.println(“key “ + element.toString( ) + “ is not in the tree”); else System.out.println(‘the tree is empty); } Deletion via Copying Technique
complexity of the problem. Jonassen and Knuth analyzed the problem of random insertions and deletions for a tree consisting of only three nodes, which required the use of Bessel functions and bivariate integral equations, and the analysis of these turned out to rank among “the more difficult of all exact analyses of algorithms that have been carried out to date.” Thus, the reliance on simulation to determine the running times of these algorithms. Balancing Trees When we first began discussing the tree data structure, we made two points in favor of trees: (1) the tree can easily represent hierarchical relationships, and (2) searching a tree (assuming a BST) is much faster than searching a list. As we have discussed since then, the second point is not always true. It is possible for a tree to become so skewed (unbalanced) that it deteriorates into a list. In order for the second point to be valid, the search tree must be well balanced. 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. There are a number of techniques that have been developed to balance binary trees. Some of the techniques consist of constantly restructuring the tree when elements arrive and lead to an unbalanced tree. Some of them consist of reordering the data and then build the tree according to some ordering of the data which will ensure that the tree is balanced when it is constructed. If the data which is used to construct a BST arrives in either ascending or descending order the tree will be skewed to the point of representing a linear list. Thus, if the smallest value in the data set is the first value read, the root of the tree will contain only a right subtree. Similarly, if the largest value in the data set is entered first, the root of the tree will contain only a left subtree. Before looking at 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.
more sophisticated algorithms to balance binary trees, lets examine a very simple technique. When the data arrive, store all of them into an array. Once all the data have arrived, sort the array using an efficient sorting algorithm. Once sorted the element at the midpoint of the array will become the root of the BST. The array can now be viewed as consisting of two subarrays, one to the left of the midpoint and one to the right of the midpoint. The middle element in the left subarray becomes the left child of the root node and the middle element in the right subarray becomes the right child of the root. This process continues with further subdivision of the original array until all the elements in the array have been positioned in the BST. A slight modification of this would be to completely generate the left subtree of the root before generating the right subtree of the root. If this is done, then the very simple recursive procedure shown below can be used to generate a balanced BST. An example of this algorithm’s execution is shown below: void balance( int data[], int first, int last) { if (first <= last) { int middle = (first + last)/2; //find middle element in the array insert(data[middle]); //add node to the tree balance(data, first, middle-1); balance(data, middle+1, last); } }
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 below: before rotation after 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 below should clarify this property: Day 17 - 13 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 Par C h (^) R P Q 2 7 2 9 35 P Q R 2 7 35 2 (^9) R P Q G r Ch Pa r R P Q
before rotation after rotation The basic operation of the DSW algorithm is to convert an arbitrary BST into a linked list-like structure called a backbone or vine. Then this elongated tree is transformed in a series of passes into a perfectly balanced tree by repeatedly rotating every second node of the backbone about its parent. In the first phase the backbone is created according to the following algorithm: This execution of this algorithm is shown in the diagram below: createBackbone (root, n) tmp = root; while (tmp != null) if tmp has a left child rotate this child about tmp; //the left child becomes the parent of tmp set tmp to the child which just became the parent; else set tmp to its right child;
This example starts with the backbone (a) generated in the previous example. 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( ) 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 mlg( m 1 ))nlg(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.