You are on page 1of 20

Binary Search and AVL Trees Lawrence M.

Brown

Binary Search and AVL Trees


Binary Search Trees Insertion and Removal AVL Trees AVL Insertion Rotations AVL Deletion Implementation

Adapted

from: Goodrich and Tamassia, Data Structures and Algorithms in Java, John Wiley & Son (1998).

25 September, 1999

Binary Search and AVL Trees Lawrence M. Brown

Binary Search Tree


A Binary Search Tree is simply an ordered binary tree for storing composition Items of an ordered Dictionary.
Each internal node stores a composition Item ( key, element ). Keys stored in the left subtree of a node are < k. Keys stored in the right subtree of a node are k. External nodes are simply place holders.

25 September, 1999

Binary Search and AVL Trees Lawrence M. Brown

Search
Algorithm: TreeSearch( k, v ) Input: A search key, k, and a node, v, of a binary search tree, T. Output: The node storing the key, k, or an external node (after all internal nodes with keys < k and before all internal nodes with keys > k). if v is an external node then return v if k = key( v ) then // node found return v else if k < key( v ) then return TreeSearch( k, T.leftChild( v ) ) else // k > key( v ) return TreeSearch( k, T.rightChild( v ) )

For this algorithm, the returned node requires one final test for an external node ( v.isExternal() ).
25 September, 1999 3

Binary Search and AVL Trees Lawrence M. Brown

Insert into a Binary Search Tree


Algorithm: insert( key-element pair ) Start by calling TreeSeach( k, T.root() ) on T. Let w be the returned node. If w is an external node, then no Item with key k is stored in T. Call T.expandExternal( w ). Store new Item ( k, e ) at node (position) w. If w is an internal node, then another Item with key k is stored at w. Call TreeSearch( k, rightChild( w ) ) and apply the algorithm to the returned node. Duplicates tend to the right.

25 September, 1999

Binary Search and AVL Trees Lawrence M. Brown

Insert into a Binary Search Tree


Example

Insert Item with key 78:

expandExternal()

A new Item will always be added at the bottom of the search tree, T. Each node visit costs O(1), thus, in the worst case, insert runs in O(h), the height of the tree, T.
5

25 September, 1999

Binary Search and AVL Trees Lawrence M. Brown

Removal from a Binary Search Tree


TreeSearch( k, T.root() ) is called to locate the node w with key k. Two complicated situations may arise: Case I: The node w is internal with a single leaf child z. Call removeAboveExternal(z) to replace w with the sibling of z.

25 September, 1999

Binary Search and AVL Trees Lawrence M. Brown

Removal from a Binary Search Tree


Case II: Both children of w are internal nodes.
Save the element stored at w into a temporary variable. Find the first internal node, y, in an inorder traversal of the right subtree of w. Replace the contents of w with the contents of y. Call removeAboveExternal( x ) on the left child of y. Return the element previously stored in w.

25 September, 1999

Binary Search and AVL Trees Lawrence M. Brown

Time Complexity of Binary Search Tree


Searching, insertion, and removal of a node in a Binary Search Tree is O(h), where h is the of the tree. height of the tree is n, then the worst-case running time for , insertion removal is O(n) -- no better than a

To prevent the worst-case running time, a re-balancing scheme is needed to yield a tree that maintains the smallest possible height.

25 September, 1999

Binary Search and AVL Trees Lawrence M. Brown

AVL Trees
An AVL Tree is a binary tree such that for every internal node v of T, the heights of the children of v can differ by at most 1.

Every

of an AVL tree is an AVL tree.


Adelson elskii and L .
9

25 September, 1999

Binary Search and AVL Trees Lawrence M. Brown

Insertion in an AVL Tree

A binary search tree T is balanced if for every node v, the height of vs children differ by at most one. Inserting a node into an AVL tree involves performing an expandExternal( w ) on T, which may change the height of some nodes in T. If an insertion causes T to become unbalanced, then travel up the tree from the newly created node, w, until the first node is reached, x, that has an unbalanced grandparent, z. Note that x could be equal to w.
Height( y ) = Height( sibling( y ) ) + 2
z y

w Expand external at w.
25 September, 1999 10

Binary Search and AVL Trees Lawrence M. Brown

Insertion in an AVL Tree


Rebalance (rotation)

In order to rebalance the subtree rooted at z, a restructuring is required. Rename x, y, and z to a, b, and c based on the order of the nodes in an in-order traversal. Let T0, T1, T2 and T3 be the subtrees located at x, y, and z. Four geometric structures are possible:

Requires single rotation.

Requires double rotation.

25 September, 1999

11

Binary Search and AVL Trees Lawrence M. Brown

Restructuring
Single Rotation Replace the subtree rooted at z with a new subtree rooted at b. Let a be the left child of b, such that T0 and T1 are left and right subtrees of a. Let c be the right child of b, such that T2 and T3 are left and right subtrees of c.

25 September, 1999

Rotate y over to z.
12

Binary Search and AVL Trees Lawrence M. Brown

Restructuring
Double Rotation Replace the subtree rooted at z with a new subtree rooted at b. Let a be the left child of b, such that T0 and T1 are left and right subtrees of a. Let c be the right child of b, such that T2 and T3 are left and right subtrees of c.

Double Rotation: rotate x over to y, and then x over to z.


25 September, 1999 13

Binary Search and AVL Trees Lawrence M. Brown

Removing a Node
Node has a single leaf Child

Remove the internal node above w by performing removeAboveExternal( w ), which may result in an unbalanced Tree. Let z be the first unbalanced node encountered while travelling up the tree from w. Let y be the child of z with the larger height, and let x be the child of y with the larger height. Perform a restructure on x to restore the balance at the subtree rooted at z. As this restructuring may upset the balance higher in the tree, continue to check for balance until the root of T is reached.

w
25 September, 1999 14

Binary Search and AVL Trees Lawrence M. Brown

Removing a Node
Examples

25 September, 1999

The two nodes with values 50 and 78 both have a height of 2. In the first example, the right subtree is assigned x, in the second example the left subtree is assigned x.
15

Binary Search and AVL Trees Lawrence M. Brown

Implementation of AVL Tree


AVL Node

An AVL Node extends the Item class to provide a variable for the node height.
public class AVLItem extends Item { private int height; public AVLItem( Object k, Object e, int h ) { super(k, e); height = h; } public int height() { return height; } public int setHeight( int h ) { int oldHeight = height; height = h; return oldHeight; } }

25 September, 1999

16

Binary Search and AVL Trees Lawrence M. Brown

Implementation of AVL Tree


public class SimpleAVLTree extends SimpleBinarySearchTree implements Dictionary { public SimpleAVLTree( Comparator c ) { super(c); T = new RestructurableNodeBinaryTree(); // Adds the ability of rotation to a BinaryTree } private int height (Position p ) { if( T.isExternal( p ) ) return 0; else return ((AVLItem) p.element()).height(); } private void setHeight( Position p ) // called only if p is internal { ((AVLItem) p.element()).setHeight(1+Math.max( height(T.leftChild(p)), height(T.rightChild(p) ))); } private boolean isBalanced( Position p ) // test whether node p has balance factor between -1 and 1 { int bf = height( T.leftChild(p) ) - height( T.rightChild(p) ); return ( (-1 <= bf) && (bf <= 1) ); }
25 September, 1999 17

Binary Search and AVL Trees Lawrence M. Brown

Implementation of AVL Tree, cont.

private Position tallerChild( Position p ) { // return a child of p with height no smaller than that of the other child if( height( T.leftChild(p) ) >= height( T.rightChild(p) ) ) return T.leftChild( p ); else return T.rightChild( p ); } private void rebalance( Position zPos ) { // traverse the path of T from zPos to the root; // for each node encountered, recompute its height and // perform a rotation if unbalanced

while ( !T.isRoot( zPos ) ) { zPos = T.parent( zPos ); setHeight( zPos ); if ( !isBalanced( zPos ) ) // perform a rotation { Position xPos = tallerChild( tallerChild( zPos ) ); zPos = ((RestructurableNodeBinaryTree) T).restructure( xPos ); setHeight( T.leftChild( zPos ) ); setHeight( T.rightChild( zPos ) ); setHeight( zPos ); } } }
25 September, 1999 18

Binary Search and AVL Trees Lawrence M. Brown

Implementation of AVL Tree, cont.


// dictionary methods public void insertItem( Object key, Object element ) throws InvalidKeyException { super.insertItem(key, element); // may throw an InvalidKeyException Position zPos = actionPos; // start at the insertion position T.replace( zPos, new AVLItem( key, element, 1) ); rebalance( zPos ); } public Object remove( Object key ) throws InvalidKeyException { Object toReturn = super.remove(key); // may throw an InvalidKeyException if ( toReturn != NO_SUCH_KEY ) { Position zPos = actionPos; rebalance( zPos ); } return toReturn; } } Note: actionPos (defined in SimpleBinarySearchTree) is the insertion position or parent of a removed position.
25 September, 1999 19

// start at the removal position

Binary Search and AVL Trees Lawrence M. Brown

Summary

A Binary Search Tree orders keys such that for any node, the left subtree has smaller key values, and the right subtree has larger key values. In the worst case, a Binary Search Tree may have height n, the number of nodes, and the running time is O(n). In the best case, the height is h = log (n+1) and the running time is O( log(n +1) ). In an AVL tree, the heights of the children can differ by at most 1. An AVL insertion/deletion may require a single or double rotation of nodes to maintain the height-balance property. The procedure for deleting a node from an AVL tree is the same as deleting a node from a Binary Search Tree followed by a restructuring if necessary. An AVL insert/delete runs in O( log n ) time.
20

25 September, 1999

You might also like