20120920-AVL樹定義《數據結構與算法分析》

AVL樹節點聲明:spa

1 struct AvlNode 2 { 3  Comparable element; 4     AvlNode *left; 5     AvlNode  *right; 6     int height; 7 
8     AvlNode( const Comparable & theElement,AvlNode *lt,AvlNode *rt,int h=0):element ( theElement),left(lt),right(rt),height(t) 9 };

計算節點高度:code

1 int height( AvlNode * t) const
2 { 3     return t == NULL ? -1 : t->height; 4 }

向AVL中插入操做:blog

void insert( const Comparable & x,AvlNode * & t) { if(t == NULL) t = new AvlNode ( x,NULL,NULL); else if (x < t->element); { insert( x ,t->left); if(height(t->left)-height(t->right) == 2) if(x < t->element) rotateWithLeftChild(t); else doubleWithLeftChild(t); } else if (t->element < x) { insert(x,t->right); if(height(t->right) - height(t->left) == 2) if(t->right->element < x) rotateWithLeftChild(t); else doubleWithLeftChild(t); } else ; t->height = max(height(t->left),height(t->right))+1; }

執行單旋轉過程:element

1 void rotateWithLeftChild(AvlNode * & k2) 2 { 3     AvlNode *k1 = k2->left; 4     k2->left = k1->right; 5     k1->right = k2; 6     k2->height = max(height(k2->left),height(k2->right))+1; 7     k1->height = max(height(k1->left),height(k1->right))+1; 8     k2=k1; 9 }

執行雙旋轉過程:it

void doubleWithLeftChild( AvlNode * & k3) { rotateWithLeftChild(k3->left); rotateWithLeftChild(k3); }
相關文章
相關標籤/搜索