AVL树的旋转与插入(C语言)
生活随笔
收集整理的這篇文章主要介紹了
AVL树的旋转与插入(C语言)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼如下:
typedef struct AVLNode *Position; typedef Position AVLTree; /* AVL樹類型 */ struct AVLNode{ElementType Data; /* 結點數據 */AVLTree Left; /* 指向左子樹 */AVLTree Right; /* 指向右子樹 */int Height; /* 樹高 */ };int Max ( int a, int b ) {return a > b ? a : b; }AVLTree SingleLeftRotation ( AVLTree A ) { /* 注意:A必須有一個左子結點B *//* 將A與B做左單旋,更新A與B的高度,返回新的根結點B */ AVLTree B = A->Left;A->Left = B->Right;B->Right = A;A->Height = Max( GetHeight(A->Left), GetHeight(A->Right) ) + 1;B->Height = Max( GetHeight(B->Left), A->Height ) + 1;return B; }AVLTree DoubleLeftRightRotation ( AVLTree A ) { /* 注意:A必須有一個左子結點B,且B必須有一個右子結點C *//* 將A、B與C做兩次單旋,返回新的根結點C *//* 將B與C做右單旋,C被返回 */A->Left = SingleRightRotation(A->Left);/* 將A與C做左單旋,C被返回 */return SingleLeftRotation(A); }/*************************************/ /* 對稱的右單旋與右-左雙旋請自己實現 */ /*************************************/AVLTree Insert( AVLTree T, ElementType X ) { /* 將X插入AVL樹T中,并且返回調整后的AVL樹 */if ( !T ) { /* 若插入空樹,則新建包含一個結點的樹 */T = (AVLTree)malloc(sizeof(struct AVLNode));T->Data = X;T->Height = 0;T->Left = T->Right = NULL;} /* if (插入空樹) 結束 */else if ( X < T->Data ) {/* 插入T的左子樹 */T->Left = Insert( T->Left, X);/* 如果需要左旋 */if ( GetHeight(T->Left)-GetHeight(T->Right) == 2 )if ( X < T->Left->Data ) T = SingleLeftRotation(T); /* 左單旋 */else T = DoubleLeftRightRotation(T); /* 左-右雙旋 */} /* else if (插入左子樹) 結束 */else if ( X > T->Data ) {/* 插入T的右子樹 */T->Right = Insert( T->Right, X );/* 如果需要右旋 */if ( GetHeight(T->Left)-GetHeight(T->Right) == -2 )if ( X > T->Right->Data ) T = SingleRightRotation(T); /* 右單旋 */else T = DoubleRightLeftRotation(T); /* 右-左雙旋 */} /* else if (插入右子樹) 結束 *//* else X == T->Data,無須插入 *//* 別忘了更新樹高 */T->Height = Max( GetHeight(T->Left), GetHeight(T->Right) ) + 1;return T; }總結
以上是生活随笔為你收集整理的AVL树的旋转与插入(C语言)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: realme 真我 V50s 手机现身电
- 下一篇: 堆的定义与操作(C语言)