Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures for Java William H. Ford William R. Topp

Similar presentations


Presentation on theme: "Data Structures for Java William H. Ford William R. Topp"— Presentation transcript:

1 Data Structures for Java William H. Ford William R. Topp
Chapter 27 Balanced Search Trees Bret Ford © 2005, Prentice Hall © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

2 Balanced Binary Search Trees
Red-black or AVL trees balance a binary search tree so it more nearly resembles a complete tree. An AVL tree maintains height-balance at each node. For each node, the difference in height of its two subtrees is in the range -1 to 1. Red-black trees are a representation of a tree and feature nodes that have the color attribute BLACK or RED. The tree maintains a measure of balance called the BLACK-height. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

3 Balanced Binary Search Trees (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

4 AVL Trees For each AVL tree node, the difference between the heights of its left and right subtrees is either -1, 0 or +1. balanceFactor = height(left subtree) - height(right subtree) If balanceFactor is positive, the node is "heavy on the left" since the height of the left subtree is greater than the height of the right subtree. With a negative balanceFactor, the node is "heavy on the right." A balanced node has balanceFactor = 0. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

5 AVL Trees (continued) © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

6 AVLTree Class The AVLTree class implements the Collection interface and builds an AVL tree. It has the same public methods as the STree class. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

7 AVLTree Class (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

8 AVLTree Class (continued)
String[] stateList = {"NV", "NY", "MA", "CA", "GA"}; int[] arr = {50, 95, 60, 90, 70, 80, 75, 78}; int i; // avlTreeA and avlTreeB are empty collections AVLTree<String> avltreeA = new AVLTree<String>(); AVLTree<Integer> avltreeB = new AVLTree<Integer>(); for (i = 0; i < stateList.length; i++) avltreeB.add(stateList[i]); for (i = 0; i < arr.length; i++) avltreeB.add(arr[i]); // output list of elements System.out.println("States: " + avltreeA); // display the tree System.out.println(avltreeB.displayTree(2)); avltreeB.drawTree(2); © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

9 AVLTree Class (continued)
Run: States: [CA, GA, MA, NV, NY] 70(-1) 60(1) (1) 50(0) (0) (0) 75(0) (0) © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

10 Implementing the AVLTree Class
An AVLNode contains the node value, references to the node's children, and the height of the subtree. height(node) = max (height(node.left), height(node.right)) + 1; © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

11 AVLNode Class // declares a binary search tree node object
private static class AVLNode<T> { // node data public T nodeValue; // child links and link to the node's parent public AVLNode<T> left, right; // public int height; public int height; © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

12 AVLNode Class (concluded)
// constructor that initializes the value, // balance factor and parent fields and sets // the link fields left and right to null public AVLNode (T item) { nodeValue = item; left = null; right = null; height = 0; } © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

13 Implementing the AVLTree Class (continued)
The recursive addNode() algorithm moves to the insertion point using the usual rules for a binary search tree. The addition of an element may cause the tree to be out of balance. The recursive addNode() algorithm reorders nodes as it returns from function calls. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

14 Implementing the AVLTree Class (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

15 Implementing the AVLTree Class (continued)
Inserting a node on the left subtree of P may cause P to be "heavy on the left" (balance factor +2). The new node is either in the outside or inside grandchild subtree. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

16 Implementing the AVLTree Class (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

17 Implementing the AVLTree Class (continued)
Inserting a node on the right subtree of P may cause P to be "heavy on the right" (balance factor -2). The new node is either in the outside or inside grandchild subtree. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

18 Implementing the AVLTree Class (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

19 AVL Tree Rotations When correcting an imbalance for a parent node, addNode() uses either a single or a double rotation. The rotation methods need to determine the height of left and right subtrees of a node. private static <T> int height(AVLNode<T> t) { if (t == null) return -1; else return t.height; } © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

20 AVL Tree Rotations (continued)
A single right rotation rotates the nodes so that the left child (LC) replaces the parent, which becomes a right child. In the process, the nodes in the right subtree of LC (RGC) are attached as a left child of P. This maintains the search tree ordering since nodes in the right subtree are greater than LC but less than P. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

21 AVL Tree Rotations (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

22 singleRotateRight() // perform a single right rotation for parent p
private static <T> AVLNode<T> singleRotateRight( AVLNode<T> p) { AVLNode<T> lc = p.left; p.left = lc.right; lc.right = p; p.height = max( height( p.left ), height( p.right ) ) + 1; lc.height = max( height( lc.left ), lc.height ) + 1; return lc; } © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

23 AVL Tree Rotations (continued)
A symmetric single left rotation occurs when the new element enters the subtree of the right outside grandchild. The rotation exchanges the parent and right child nodes, and attaches the subtree LGC as a right subtree for the parent node. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

24 AVL Tree Rotations (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

25 singleRotateLeft() // perform a single left rotation for parent p
private static <T> AVLNode<T> singleRotateLeft( AVLNode<T> p) { AVLNode<T> rc = p.right; p.right = rc.left; rc.left = p; p.height = max(height(p.left), height(p.right)) + 1; rc.height = max(height(rc.right), rc.height) + 1; return rc; } © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

26 AVL Tree Rotations (continued)
When a new item enters the subtree for an inside grandchild, the imbalance is fixed with a double rotation which consists of two single rotations. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

27 AVL Tree Rotations (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

28 doubleRotateRight() // perform a double right rotation for parent p
private static <T> AVLNode<T> doubleRotateRight( AVLNode<T> p) { p.left = singleRotateLeft(p.left); return singleRotateRight(p); } © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

29 doubleRotateLeft() // perform a single left rotation for parent p
private static <T> AVLNode<T> doubleRotateLeft( AVLNode<T> p) { p.right = singleRotateRight(p.right); return singleRotateLeft(p); } © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

30 addNode() Recursive addNode() descends to the insertion point and inserts the node. As it returns, it visits the nodes in reverse order, fixing any imbalances using rotations. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

31 addNode() (continued)
private AVLNode<T> addNode(AVLNode<T> t, T item) { if( t == null ) t = new AVLNode<T>(item); else if (((Comparable<T>)item).compareTo( t.nodeValue) < 0) t.left = addNode( t.left, item); if (height(t.left) - height(t.right) == 2 ) if (((Comparable<T>)item).compareTo( t.left.nodeValue) < 0) t = singleRotateRight(t); else t = doubleRotateRight(t); } t.nodeValue) > 0 ) t.right = addNode(t.right, item ); © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

32 addNode() (concluded)
if (height(t.left) - height(t.right) == -2) if (((Comparable<T>)item).compareTo( t.right.nodeValue) > 0) t = singleRotateLeft(t); else t = doubleRotateLeft(t); } // duplicate; throw IllegalStateException throw new IllegalStateException(); t.height = max( height(t.left), height(t.right) ) + 1; return t; © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

33 add() Method add() assures that item is not in the tree, calls addNode() to insert it, and then increments treeSize and modCount. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

34 add() (concluded) // if item is not in the tree, insert it and
// return true; if item is a duplicate, do not // insert it and return false public boolean add(T item) { try root = addNode(root, item); } catch (IllegalStateException ise) { return false; } // increment the tree size and modCount treeSize++; modCount++; // we added a node to the tree return true; © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

35 Example - Building an AVL Tree
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

36 Example - Building an AVL Tree (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

37 Example - Building an AVL Tree (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

38 Example - Building an AVL Tree (concluded)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

39 Efficiency of AVL Tree Insertion
A mathematical analysis shows that int(log2n)  height < log2(n+2) indicating that the worst case running time for insertion is O(log2n). The worst case for the difficult deletion algorithm is also O(log2n). © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

40 2-3-4 Trees In a tree, a 2‑node has two children and one value, a 3-node has 3 children and 2 values, and a 4-node has 4 children and 3 values. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

41 Searching a Tree To find a value called item, start at the root and compare item with the values in the existing node. If no match occurs, move to the appropriate subtree. Repeat the process until you find a match or encounter an empty subtree. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

42 Searching a 2-3-4 Tree (concluded)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

43 Inserting into a 2-3-4 Tree
To insert item, move down the tree, splitting any 4-node encountered by moving the middle element up one level and creating two child 2-nodes. This includes splitting the root if it is a 4-node. Split all 4-nodes on the descent to the insertion point, which will be a 2- or a 3-node. This avoids a pass back up the tree splitting nodes. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

44 Inserting into a 2-3-4 Tree (continued)
Splitting a 4-node. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

45 Building a Tree © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

46 Building a 2-3-4 Tree (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

47 Building a 2-3-4 Tree (concluded)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

48 Efficiency of Trees In a tree with n elements, the maximum number of nodes visited during the search for an element is int (log2n) + 1. Inserting an element into a 2‑3‑4 tree with n elements requires splitting no more than int(log2n) nodes and normally requires far fewer splits. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

49 Red-Black Trees A red-black tree is a binary search tree in which each node has the color attribute BLACK or RED. It was designed as a representation of a tree, using different color combinations to describe 3-nodes and 4-nodes. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

50 Red-Black Trees (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

51 Representing 2-3-4 Tree Nodes
A 2-node is always black. A 4-node has the middle value as a black parent and the other values as red children. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

52 Representing 2-3-4 Tree Nodes (concluded)
Represent a 3-node with a BLACK parent and a smaller RED left child or with a BLACK parent and a larger RED right child. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

53 Representing a 2-3-4 Tree as a Red-Black Tree
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

54 Representing a 2-3-4 Tree as a Red-Black Tree (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

55 Representing a 2-3-4 Tree as a Red-Black Tree (concluded)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

56 Properties of a Red-Black Tree
These properties follow from the representation of a tree as a red-black tree. Root of red-black tree is always BLACK. A RED parent never has a RED child. Thus in a red‑black tree there are never two successive RED nodes. Every path from the root to an empty subtree contains the same number of BLACK nodes. The number, called the black height, defines balance in a red-black tree. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

57 Properties of a Red-Black Tree (concluded)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

58 Inserting a Node in a Red-Black Tree
When scanning down a path to find the insertion location, split a 4-node (a BLACK parent with two RED children) by coloring the children BLACK and the parent RED. This is the red-black tree equivalent of splitting a 4-node in a tree. Splitting 4-nodes may involve performing rotations and color changes. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

59 Inserting a Node in a Red-Black Tree (continued)
Enter a new element into the tree as a RED leaf node. Inserting a RED node at the bottom of a tree may result in two successive RED nodes. When this occurs, use a rotation and recoloring to reorder the tree. Maintain the root as a BLACK node. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

60 Inserting a Node in a Red-Black Tree (continued)
Four Situations in the Splitting of a 4-Node © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

61 Inserting a Node in a Red-Black Tree (continued)
If the parent is BLACK, a color flip does not cause a rotation. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

62 Inserting a Node in a Red-Black Tree (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

63 Inserting a Node in a Red-Black Tree (continued)
A color-flip of a 4-node with a RED parent leaves successive red nodes. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

64 Rebalancing with a Single Rotation
When a 4-node is an outside child of its parent P and the color flip imbalances the tree, use a single rotation about node P. In the process, change the color for nodes P and G. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

65 Rebalancing with a Single Rotation (continued)
Single left and right rotations with color changes © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

66 Rebalancing with a Single Rotation (concluded)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

67 Rebalancing with a Double Rotation
A double rotation is used when the 4-node is an inside child of the parent and the color flip creates a color conflict. As with single rotations, double rotations are symmetric depending on whether the parent P is a left or a right child of G. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

68 Rebalancing with a Double Rotation (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

69 Rebalancing with a Double Rotation (concluded)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

70 Insertion at the Bottom of the Tree
Inserting a node into the tree with color RED may require a rotation. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

71 Insertion at the Bottom of the Tree (concluded)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

72 Building a Red-Black Tree
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

73 Building a Red-Black Tree (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

74 Building a Red-Black Tree (concluded)
Insert 30 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

75 Red-Black Tree Search Running Time
The worst‑case running time to search a red-black tree or insert an item is O(log2n). The maximum length of a path in a red-black tree with black height B is 2*B-1. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

76 Erasing a Node in a Red-Black Tree
Erasing a node from an ordinary binary search tree is more difficult than inserting a node. No further action necessary when replacement node is RED. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

77 Erasing a Node in a Red-Black Tree (concluded)
Erasing a node from a red-black tree requires recoloring and rotations when the replacement node is BLACK. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

78 The RBTree Class RBTree is a generic class that implements the Collection interface and uses RBNode objects to create a red-black tree. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

79 The RBTree Class (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

80 The RBTree Class (concluded)
The Web supplement contains the document "RBTree Class.pdf" which provides an expanded explanation of the RBTree class implementation. The document includes a discussion of the private section of the class and the algorithms for splitting a 4‑node and performing a top‑down insertion. © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

81 Program 27.1 import ds.util.RBTree; public class Program27_1 {
public static void main (String[] args) // list of elements for the red-black tree int[] intArr = {10, 25, 40, 15, 50, 45, 30, 65, 70, 55}; RBTree<Integer> rbtree = new RBTree<Integer>(); int i; // load the tree with values from intArr; display // available after each insert for(i = 0; i < intArr.length; i++) rbtree.add(intArr[i]); rbtree.drawTrees(4); } © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

82 Program 27.1 (concluded) // display the final tree in the console window System.out.println(rbtree.displayTree(2)); // remove red-node 25 rbtree.remove(25); rbtree.drawTrees(4); // remove black-node root rbtree.remove(45); rbtree.drawTree(3); } © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

83 Program 27.1 Run © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

84 Program 27.1 Run (continued)
45 25* * 15* 30* * © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

85 Program 27.1 Run (concluded)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.


Download ppt "Data Structures for Java William H. Ford William R. Topp"

Similar presentations


Ads by Google