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.

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 2-3-4 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.

Balanced Binary Search Trees (continued)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

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.

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

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

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

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

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

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

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

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

NJ. All rights reserved. Inc. © 2005 Pearson Education. The recursive addNode() algorithm reorders nodes as it returns from function calls.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. Upper Saddle River.. .

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

. The new node is either in the outside or inside grandchild subtree. Upper Saddle River. All rights reserved. Inc. © 2005 Pearson Education.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). NJ. .

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

. Inc. © 2005 Pearson Education.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). All rights reserved. . Upper Saddle River. The new node is either in the outside or inside grandchild subtree. NJ.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Example - Building an AVL Tree (continued)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Example - Building an AVL Tree (concluded)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Efficiency of AVL Tree Insertion

A mathematical analysis shows that indicating that the worst case running time for insertion is O(log2n). The worst case for the difficult deletion algorithm is also O(log2n).
int(log2n)  height < 1.4405 log2(n+2) - 1.3277

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

2-3-4 Trees

In a 2-3-4 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.

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

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

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

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

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

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

NJ. Inc.. All rights reserved.Building a 2-3-4 Tree (concluded) 12 4 25 4 12 25 2 8 10 15 35 55 2 8 10 11 15 35 55 Split 4-node (4. 12. . 25) Insert 11 © 2005 Pearson Education. Upper Saddle River.

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

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

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

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

B) in a 2-3-4 Tree A B S S T U T U S T (a) Red-black tree representation A is a black parent. Upper Saddle River. A is a red left child B U © 2005 Pearson Education.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. Inc. All rights reserved.. NJ. . 3-node (A. B is a red right child A B A (b) Red-black tree representation B is a black parent.

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

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

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

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

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

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

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

. All rights reserved.Inserting a Node in a Red-Black Tree (continued) P C X C P P C X P C X B X A B A A B A B Parent P is BLACK X is a left-child Parent P is BLACK X is a right-child Parent P is RED X is a left-child Parent P is RED X is a right-child Four Situations in the Splitting of a 4-Node © 2005 Pearson Education. Upper Saddle River. NJ. . Inc.

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

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

NJ.Inserting a Node in a Red-Black Tree (continued) G G G G P D Color flip C A X P D C C P C Color flip P X X D B A X D B A B B A Color flip involves an outside child of P in the left subtree of G Color flip involves an inside child of P in the right subtree of G A color-flip of a 4-node with a RED parent leaves successive red nodes. All rights reserved. © 2005 Pearson Education. Upper Saddle River.. . Inc.

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

Upper Saddle River.. All rights reserved. Inc.Rebalancing with a Single Rotation (continued) G G P D C A X P C D D P G P X G X X C A B B D C A A B B (a) Single right rotation and color change (b) Single left rotation and color change Single left and right rotations with color changes © 2005 Pearson Education. NJ. .

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

. 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. All rights reserved.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. Inc.. NJ. Upper Saddle River.

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

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

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

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

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

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

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

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

Upper Saddle River. .Erasing a Node in a Red-Black Tree  Erasing a node from an ordinary binary search tree is more difficult than inserting a node. Inc.. Delete 75 Replacement node 78 is RED 75 60 50 70 80 78 90 100 60 50 70 80 90 100 78 © 2005 Pearson Education. NJ.  No further action necessary when replacement node is RED. All rights reserved.

Inc. NJ. Delete 90 Replacement node is BLACK 75 75 Replace 90 with 100 Right rotation with pivot 80 and recoloring 50 75 60 90 60 100 60 80 50 70 80 100 50 70 80 70 78 100 78 78 © 2005 Pearson Education. All rights reserved.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. . Upper Saddle River..

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

util . NJ. Methods String displayTree(int maxCharacters) Returns a string that gives a hierarchical view of the tree.. Upper Saddle River. ds. Nodes are colored. All rights reserved. String toString() Returns a string that describes the elements in a comma-separated list enclosed in brackets. void drawTree(int maxCharacters) Creates a single frame that gives a graphical display of the tree. © 2005 Pearson Education. String drawTrees(int maxCharacters) Creates of the action of the function and any return value.The RBTree Class (continued) class RBTree<T> implements Collection<T> Constructor RBTree() Creates an empty red-black tree. An asterisk (*) marks red nodes. Inc.

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. Upper Saddle River. .. Inc. © 2005 Pearson Education. All rights reserved.pdf" which provides an expanded explanation of the RBTree class implementation. NJ.The RBTree Class (concluded)  The Web supplement contains the document "RBTree Class.

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

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

1 Run © 2005 Pearson Education. . NJ.Program 27.. Inc. Upper Saddle River. All rights reserved.

Program 27. NJ. All rights reserved. Inc.1 Run (continued) 45 25* 10 40 15* 30* 50 65* 70 55* © 2005 Pearson Education. Upper Saddle River. ..

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

Sign up to vote on this title
UsefulNot useful