110 likes | 301 Vues
CSE 3358 AVL TREE IMPLEMENTATION. Data Structures and Algorithms. AVL Tree Node Structure. template < typename comparable> class AvlTree { private : struct AvlNode { Comparable element; AvlNode *left; AvlNode *right; int height;
E N D
CSE 3358 AVL TREE IMPLEMENTATION Data Structures and Algorithms
AVL Tree Node Structure • template <typename comparable> • class AvlTree { • private: • structAvlNode • { • Comparable element; • AvlNode *left; • AvlNode *right; • int height; • AvlNode( const Comparable & theElement, • AvlNode*lt, • AvlNode *rt, • int h = 0 ) • : element( theElement ), • left( lt ), • right( rt ), • height( h ) • { } • }; • AvlNode * root; //root of the tree
AVL Tree Public Interface • //Various constructors • /** • * Test if the tree is logically empty. • * Return true if empty, false otherwise. • */ • boolisEmpty( ) const • { • return root == NULL; • } • const Comparable & findMin( ) const • { • if( isEmpty( ) ) • throw UnderflowException( ); • return findMin( root )-> element; • }
AVL Tree Public Interface • void insert( const Comparable & x ) • { • insert( x, root ); • } • Observation: • Public interfaces make call to private versions of the same function.
AVL Tree Private Member Functions - findMin AvlNode * findMin( AvlNode *t ) const { if( t == NULL ) return NULL; if( t->left == NULL ) return t; return findMin( t->left ); }
k2 Rotate With Left Child k1 Z Y X k1 k2 X Y Z
AVL Tree Private Member Functions - Insert 1 voidinsert( const Comparable & x, AvlNode * & t ) 2 { 3 if( t == NULL ) 4 t = new AvlNode( x, NULL, NULL ); 5 else if( x < t->element ) 6 { 7 insert( x, t->left ); 8 if( height( t->left ) - height( t->right ) == 2 ) 9 if( x < t->left->element ) 10 rotateWithLeftChild( t ); 11 else 12 doubleWithLeftChild( t ); 13 }
//continued from previous side 14 else if( t->element < x ) 15 { 16 insert( x, t->right ); 17 if( height( t->right ) - height( t->left ) == 2 ) 18 if( t->right->element < x ) 19 rotateWithRightChild( t ); 20 else 21 doubleWithRightChild( t ); 22 } 23 else 24 ; // Duplicate; do nothing 25 t->height = max( height( t->left ), 26 height( t->right ) ) + 1; 27 }
AVL Tree Private Member Functions – rotateWithLeftChild void rotateWithLeftChild( AvlNode * & k2 ) { AvlNode *k1 = k2->left; k2->left = k1->right; k1->right = k2; k2->height = max( height( k2->left ), height( k2->right ) ) + 1; k1->height = max( height( k1->left ), k2->height ) + 1; k2 = k1; }
AVL Tree Private Member Functions – doubleRotateWithLeftChild void doubleWithLeftChild( AvlNode * & k3 ) { rotateWithRightChild( k3->left ); rotateWithLeftChild( k3 ); }