一、平衡二叉树的定义
二、平衡二叉树的操作集
1. typedef struct AVLNode *Position;
2. typedef Position AVLTree; /* AVL树类型 */
3. struct AVLNode{
4. ElementType Data; /* 结点数据 */
5. AVLTree Left; /* 指向左子树 */
6. AVLTree Right; /* 指向右子树 */
7. int Height; /* 树高 */
8. };
9.
10. int Max ( int a, int b )
11. {
12. return a > b ? a : b;
13. }
14.
15. AVLTree SingleLeftRotation ( AVLTree A )
16. { /* 注意:A必须有一个左子结点B */
17. /* 将A与B做左单旋,更新A与B的高度,返回新的根结点B */
18.
19. AVLTree B = A->Left;
20. A->Left = B->Right;
21. B->Right = A;
22. A->Height = Max( GetHeight(A->Left), GetHeight(A->Right) ) + 1;
23. B->Height = Max( GetHeight(B->Left), A->Height ) + 1;
24.
25. return B;
26. }
27.
28. AVLTree DoubleLeftRightRotation ( AVLTree A )
29. { /* 注意:A必须有一个左子结点B,且B必须有一个右子结点C */
30. /* 将A、B与C做两次单旋,返回新的根结点C */
31.
32. /* 将B与C做右单旋,C被返回 */
33. A->Left = SingleRightRotation(A->Left);
34. /* 将A与C做左单旋,C被返回 */
35. return SingleLeftRotation(A);
36. }
37.
38. /*************************************/
39. /* 对称的右单旋与右-左双旋请自己实现 */
40. /*************************************/
41.
42. AVLTree Insert( AVLTree T, ElementType X )
43. { /* 将X插入AVL树T中,并且返回调整后的AVL树 */
44. if ( !T ) { /* 若插入空树,则新建包含一个结点的树 */
45. T = (AVLTree)malloc(sizeof(struct AVLNode));
46. T->Data = X;
47. T->Height = 0;
48. T->Left = T->Right = NULL;
49. } /* if (插入空树) 结束 */
50.
51. else if ( X < T->Data ) {
52. /* 插入T的左子树 */
53. T->Left = Insert( T->Left, X);
54. /* 如果需要左旋 */
55. if ( GetHeight(T->Left)-GetHeight(T->Right) == 2 )
56. if ( X < T->Left->Data )
57. T = SingleLeftRotation(T); /* 左单旋 */
58. else
59. T = DoubleLeftRightRotation(T); /* 左-右双旋 */
60. } /* else if (插入左子树) 结束 */
61.
62. else if ( X > T->Data ) {
63. /* 插入T的右子树 */
64. T->Right = Insert( T->Right, X );
65. /* 如果需要右旋 */
66. if ( GetHeight(T->Left)-GetHeight(T->Right) == -2 )
67. if ( X > T->Right->Data )
68. T = SingleRightRotation(T); /* 右单旋 */
69. else
70. T = DoubleRightLeftRotation(T); /* 右-左双旋 */
71. } /* else if (插入右子树) 结束 */
72.
73. /* else X == T->Data,无须插入 */
74.
75. /* 别忘了更新树高 */
76. T->Height = Max( GetHeight(T->Left), GetHeight(T->Right) ) + 1;
77.
78. return T;
79. }