AVL--平衡二叉查找树
2013-08-19 21:49
274 查看
平衡二叉树失衡的四种情况:
AVL树节点声明:
对于第一种情况(左左)---(右右类似):
执行的变换代码为:
对于第三种情况(第四种类似):
执行的变换代码为:
向AVL树中插入节点的函数:
AVL树节点声明:
struct AvlNode; typedef struct AvlNode *Position; typedef struct AvlNode *AvlTree; struct AvlNode { ElementType Element; AvlTree Left; AvlTree Right; int Height; }; static int Height(Position P) { if (P == NULL) return -1; else return P->Height; }
对于第一种情况(左左)---(右右类似):
执行的变换代码为:
/* 左左情况下 */ static Position SingleRotateWithLeft(Position K2) { Position K1; 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), Height(K1->Right)) + 1; return K1; /* New Root */ } /* 右右的情况下 */ static Position SingleRotateWithRight(Position K2) { Position K1; K1 = K2->Right; K2->Right = K1->Left; K1->Left = K2; K2->Height = Max(Height(K2->Left), Height(K2->Right)) + 1; K1->Height = Max(Height(K1->Left), Height(K1->Right)) + 1; return K1; /* New Root */ }
对于第三种情况(第四种类似):
执行的变换代码为:
/* 左右情况 */ static Position DoubleRotateWithLeft(Position K3) { /* Rotate between K1 and K2 */ K3->Left = SingleRotateWithRight(K3->Left); /* Rotate between K3 and K2 */ return SingleRotateWithLeft(K3); } /* 右左情况 */ static Position DoubleRotateWithRight(Position K3) { /* Rotate between K1 and K2 */ K3->Right = SingleRotateWithRight(K3->Right); /* Rotate between K3 and K2 */ return SingleRotateWithRight(K3); }
向AVL树中插入节点的函数:
AvlTree Insert(Element x, AvlTree T) { if (T == NULL) { T = malloc(sizeof(struct AvlNode)); if (T == NULL) printf("Out of space!\n"); else { T->Element = x; T->Height = 0; T->Left = T->Right = NULL; } } else if (x < T->Element) { T->Left = Insert(x, T->Left); if (Height(T->Left) - Height(T->Right) == 2) if (x < T->Left->Element) T = SingleRotateWithLeft(T); else T = DoubleRotateWithLeft(T); } else if (x > T->Element) { T->Right = Insert(x, T->Right); if (Height(T->Right) - Height(T->Left) == 2) if (x > T->Right->Element) T = SingleRotateWithRight(T); else T = DoubleRotateWithRight(T); } /* Else x is in the tree already; we'll do nothing */ T->Height = Max(Height(T->Left), Height(T->Right)) + 1; return T; }
相关文章推荐
- 常用树类数据结构总结-二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)的性能分析
- 二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)的比较
- 二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)的比较
- 平衡二叉查找树(AVL)的查找、插入、删除
- 平衡二叉查找树(AVL)
- 动态查找树比较: 二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)
- 二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)的比较
- 平衡二叉查找树 AVL 的实现
- PAT - 甲级 - 1066. Root of AVL Tree (25)(AVL平衡二叉查找树)
- 【查找结构3】平衡二叉查找树 [AVL]
- 二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)的比较
- 【查找结构3】平衡二叉查找树 [AVL]
- 常用树类数据结构总结-二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)的性能分析
- 二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)
- 二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)的比较
- 二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)的比较
- 平衡二叉查找树 [AVL]
- 平衡二叉查找树插入节点操作( AVLTree ):旋转、调整平衡
- 【查找结构3】平衡二叉查找树 [AVL]
- 二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)的比较