Upload
vishal-bharam
View
224
Download
0
Embed Size (px)
Citation preview
7/22/2019 Binary Search and AVL Trees
1/20
25 September, 19991
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).
7/22/2019 Binary Search and AVL Trees
2/20
25 September, 19992
Binary Search and AVL Trees
Lawrence M. Brown
Binary Search Tree
A Binary Search Tree is simply an ordered binary tree for storingcomposition Items of an ordered Dictionary.
Each internal node stores a composition Item ( key, element ).
Keys stored in the leftsubtree of a node are < k.
Keys stored in the rightsubtree of a node are k.
External nodes are simply place holders.
7/22/2019 Binary Search and AVL Trees
3/20
25 September, 19993
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 < kand before all internal nodes with keys > k).
if v is an external node then
returnv
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() ).
7/22/2019 Binary Search and AVL Trees
4/20
25 September, 19994
Binary Search and AVL Trees
Lawrence M. Brown
Insert into a Binary Search Tree
Algorithm: insert( key-elementpair )
Start by calling TreeSeach( k, T.root() ) on T. Let w be the returned
node.
Ifw is an external node, then no Item with key kis stored in T.
Call T.expandExternal( w ).
Store new Item ( k, e ) at node (position) w.
Ifw is an internal node, then anotherItem with key kis stored at w.
Call TreeSearch( k, rightChild( w ) ) and apply the algorithm tothe returned node. Duplicates tend to the right.
7/22/2019 Binary Search and AVL Trees
5/20
25 September, 19995
Binary Search and AVL Trees
Lawrence M. Brown
Insert into a Binary Search TreeExample
Insert Item with key 78:
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.
expandExternal()
7/22/2019 Binary Search and AVL Trees
6/20
25 September, 19996
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 leafchildz.
Call removeAboveExternal(z) to replace w with the
siblingofz.
z
7/22/2019 Binary Search and AVL Trees
7/20
25 September, 19997
Binary Search and AVL Trees
Lawrence M. Brown
Removal from a Binary Search Tree
Case II: Both children ofw are internal nodes.
Save the element stored at w into a temporary variable.
Find the firstinternal node,y, in an inorder traversal of the right subtree ofw.
Replace the contents ofw with the contents ofy.
Call removeAboveExternal(x ) on the left child ofy.
Return the element previously stored in w.
xy
7/22/2019 Binary Search and AVL Trees
8/20
25 September, 19998
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.
7/22/2019 Binary Search and AVL Trees
9/20
25 September, 19999
Binary Search and AVL Trees
Lawrence M. Brown
AVL Trees
AnAVL Tree is a binary tree such that for every internal node v ofT,
the heights of the children ofv can differ by at most 1.
Adelson elskii and L .
Every of an AVL tree is an AVL tree.
7/22/2019 Binary Search and AVL Trees
10/20
25 September, 199910
Binary Search and AVL Trees
Lawrence M. Brown
Insertion in an AVL Tree
A binary search tree Tis balanced if for every node v, the height ofvschildren differ by at most one.
Insertinga node into anAVL tree involves performing an
expandExternal( w ) on T, which may change the height of some nodes
in T.
If an insertion causes Tto 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 thatx could be equal to w.
Height(y ) = Height( sibling(y) ) + 2
w
z
y
Expand external at w.
7/22/2019 Binary Search and AVL Trees
11/20
25 September, 199911
Binary Search and AVL Trees
Lawrence M. Brown
Insertion in an AVL TreeRebalance (rotation)
In order to rebalance the subtree rooted atz, a restructuringis required.
Renamex,y, andzto 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
atx,y, and z.
Four geometric structures are possible:
Requires single rotation.
Requires double rotation.
7/22/2019 Binary Search and AVL Trees
12/20
25 September, 1999
12
Binary Search and AVL Trees
Lawrence M. Brown
Restructuring
Single Rotation Replace the subtree rooted atzwith a new subtree rooted at b.
Let a be the left child ofb, such that T0 and T1 are left and right subtrees ofa.
Let c be the right child ofb, such that T2 and T3 are left and right subtrees ofc.
Rotate yover to z.
7/22/2019 Binary Search and AVL Trees
13/20
25 September, 1999
13
Binary Search and AVL Trees
Lawrence M. Brown
RestructuringDouble Rotation
Replace the subtree rooted atzwith a new subtree rooted at b.
Let a be the left child ofb, such that T0 and T1 are left and right subtrees ofa.
Let c be the right child ofb, such that T2 and T3 are left and right subtrees ofc.
Double Rotation: rotate x over to y, and then x over to z.
7/22/2019 Binary Search and AVL Trees
14/20
25 September, 1999
14
Binary Search and AVL Trees
Lawrence M. Brown Removing a NodeNode has a single leaf Child
Remove the internalnode above w by performing removeAboveExterna l( w ), which
may result in an unbalanced Tree.
Letzbe the firstunbalanced node encountered while travelling up the tree from w.
Lety be the child ofzwith the largerheight, and letx be the child ofy with the larger
height.
Perform a restructure onx to restore the balance at the subtree rooted atz. As this restructuring may upset the balance higher in the tree, continue to check for
balance until the root ofTis reached.
w
7/22/2019 Binary Search and AVL Trees
15/20
25 September, 1999
15
Binary Search and AVL Trees
Lawrence M. Brown
Removing a NodeExamples
w
w
The two nodes with values 50 and 78 both have a height of 2.
In the first example, the right subtree is assignedx, in
the second example the left subtree is assigned x.
7/22/2019 Binary Search and AVL Trees
16/20
25 September, 1999
16
Binary Search and AVL Trees
Lawrence M. Brown
Implementation of AVL Tree
AVL Node
AnAVL 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;
}
}
7/22/2019 Binary Search and AVL Trees
17/20
25 September, 1999
17
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 ifp is internal
{ ((AVLItem) p.element()).setHeight(1+Math.max( height(T.leftChild(p)), height(T.rightChild(p) )));
}
private boolean isBalanced( Position p ) // test whether nodep has balance factor between -1 and 1
{ int bf = height( T.leftChild(p) ) - height( T.rightChild(p) );
return ( (-1
7/22/2019 Binary Search and AVL Trees
18/20
25 September, 1999
18
Binary Search and AVL Trees
Lawrence M. Brown
Implementation of AVL Tree, cont.
private Position tallerChild( Position p ){
// return a child ofp 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 ofT 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 );
}
}
}
7/22/2019 Binary Search and AVL Trees
19/20
25 September, 1999
19
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; // start at the removal position
rebalance( zPos );
}
return toReturn;
}
}
Note: actionPos (defined in SimpleBinarySearchTree) is the insertion
position or parent of a removed position.
7/22/2019 Binary Search and AVL Trees
20/20
25 September, 1999
20
Binary Search and AVL Trees
Lawrence M. Brown Summary
A Binary Search Tree orders keys such that for any node, the left
subtree has smallerkey values, and the rightsubtree haslargerkeyvalues.
In the worst case, a Binary Search Tree may have heightn, 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 anAVL tree, the heights of the children can differ by at most 1.
An AVL insertion/deletion may require a single ordouble rotation of
nodes to maintain the height-balanceproperty.
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.