资源下载:源代码及原理解释
一、应用场景
在程序设计中,经常需要在大量数据中进行查找相关的工作。如判断一个元素是否存在于数据集中;获取指定值上界(比指定值大的最相近元素);获取指定值下界。而二叉查找树能很好的满足要求。而且对二叉查找树进行中序遍历就可以得到有序的元素序列。二叉查找树的插入后,如果不做任何处理则树的形状和插入的元素序列相关,而不能保证查找消耗与对数成线性关系。如果能有效地在插入过程后对树进行适当处理则可以控制树的高度,即最长查找路径的长度。这样就叫自平衡二叉树。
自平衡二叉树中最常见的是AVL树和redblack树。据大师们统计redblack树的性能要优于AVL树。这篇文章先讲讲AVL树。维基百科中这样描述它:
二、定义
在计算机科学中,AVL树是最先发明的自平衡二叉查找树。在AVL树中任何节点的两个子树的高度最大差别为一,所以它也被称为高度平衡树。查找、插入和删除在平均和最坏情况下都是O(log n)。增加和删除可能需要通过一次或多次树旋转来重新平衡这个树。AVL树得名于它的发明者G.M. Adelson-Velsky和E.M. Landis,他们在1962年的论文《An algorithm for the organization of information》中发表了它。
节点的平衡因子是它的右子树的高度减去它的左子树的高度。带有平衡因子1、0或 -1的节点被认为是平衡的。带有平衡因子 -2或2的节点被认为是不平衡的,并需要重新平衡这个树。平衡因子可以直接存储在每个节点中,或从可能存储在节点中的子树高度计算出来。
三、关键问题
AVL树的操作中异于普通二叉查找树的地方是插入和删除过程。
插入
插入过程可能会导致不平衡的情况出现,这样我们就需要对这些情况进行处理—–即旋转。先来个详细的图:(Root是失去平衡的树的根结点,pivot是旋转后重新平衡的树的根结点。
总共有四种情况插入导致不平衡:(不平衡结点为上图中的root)
(1)不平衡结点的左子树的左子树高度增加,导致不平衡结点的左子树结点高度增加,如果不平衡结点的左子树结点高度原来就比不平衡结点的右子树结点高度大一,则现在变为大2.导致不平衡结点的平衡因子由-1变为-2。需要对不平衡结点进行右旋,即把不平衡结点移动到它的右孩子的位置,将左孩子移动到它的位置上,并将左孩子的右子树接到不平衡结点的左孩子上。
(2)不平衡结点的右子树的右子树高度增加,导致不平衡结点的右子树结点高度增加,如果不平衡结点的右子树结点高度原来就比不平衡结点的左子树结点高度大一,则现在变为大2.导致不平衡结点的平衡因子由1变为2。需要对不平衡结点进行左旋,即把不平衡结点移动到它的左孩子的位置,将右孩子移动到它的位置上,并将右孩子的左子树接到不平衡结点的右孩子上。
下面两种情况进行一次旋转并不能使树恢复平衡,需要进行两次旋转。
(3)不平衡结点的左子树的右子树高度增加,导致不平衡结点的左子树结点高度增加,如果不平衡结点的左子树结点高度原来就比不平衡结点的右子树结点高度大一,则现在变为大2.导致不平衡结点的平衡因子由-1变为-2。先进行左旋使树变为(1)的情况,再进行右旋。
(4)不平衡结点的右子树的左子树高度增加,导致不平衡结点的右子树结点高度增加,如果不平衡结点的右子树结点高度原来就比不平衡结点的左子树结点高度大一,则现在变为大2.导致不平衡结点的平衡因子由1变为2。先进行右旋使树变为(2)的情况,再进行左旋。
知道了四种需要进行旋转的情况,我们知道有不平衡结点后该如何进行位置调整。但是如何知道查找平衡结点呢?当我们进行插入时,需要将插入元素不断地与树中的结点进行比较,然后决定插入它的左子树还是它的右子树,这条路径记录了插入元素和哪些结点相关(即哪些结点的左子树或右子树插入了元素)。这条路径上的结点的平衡因子可能会发生变化,记住是可能。
调整平衡因子
插入结点后,插入路径上的结点的平衡因子需要进行调整以表达现在的平衡情况。是不是在插入路径范围进行变化呢?不是。之后的回溯过程会从插入路径回溯,直到找到不平衡点,找到不平衡点后,不平衡点的祖先结点们的平衡因子是不用改变的。从插入结点到不平衡结点中的每个结点之间的平衡因子需要怎么变化呢?因为它们的平衡因子之前都是0.现在插入了新结点,这些结点的高度都会加1.如果插入元素小于结点值,则结点平衡因子-1,大于则结点平衡因子+1(分别对应插入了结点的哪个子树中)。至于为什么么这些结点的平衡因子都是之前都是零0,看获得不平衡点。
获得不平衡点:
分析旋转的四种情况,不然发现,旋转前和旋转后,子树t的高度是没有变化的。也就是说只需要找到路径中和插入结点最近的不平衡点,然后以该不平衡结点进行旋转处理,则路径中该不平衡结点的祖先结点们的平衡因子是不变的。该结点即为不平衡点,即旋转中的root结点。由此可见插入新元素后不平衡点可能大于一个,但是经过对离插入结点最近的不平衡点进行旋转调整后,不平衡点全部消失。如何判断谁是可能是最近的不平衡点呢?插入路径中离插入结点最近的插入时平衡因子不等于0的结点即为可能的不平衡点。为什么呢?因为如果结点平衡因子是0,插入一个结点不会导致该结点的平衡因子变为+2,或者-2。但是会改变它的父结点的平衡因子,会使父结点的平衡因子变化1。如果父结点的平衡因子之前是0.则继续向上回溯。
(1)如果父结点的平衡因子因为变化1而变为0,则是在父结点的较短的子树中插入了新结点导致子树高度加1,使父结点平衡因子变为了0。父结点为根的子树高度没有变化,则祖先们的平衡因子不需要变化,所以得到没有平衡因子的结论。
(2)如果父结点的平衡因子因为变化1而变为-2或者+2,那么父结点成为了不平衡结点,需要以父结点为根进行旋转变化。至于使用哪种变化,首先根据父结点与插入值的大小关系,插入值小于该结点,则为L,大于则为R。再根据插入值与该结点的左孩子(L)或者右孩子(R)进行大小比较得出。LL、LR、RR、RL四种情况之一进行位置调整。
旋转后平衡因子调整
上面获取不平衡结点后,进行了位置调整,但是位置调整后平衡因子也需要再次调整。
一、LL型平衡因子调整
二、LR型平衡因子调整
三、RR型平衡因子调整
四、RL型平衡因子调整
删除
完整代码一:AVL tree C语言实现。这是GNU的实现。由两个文件组成。
头文件:
/* Produced by texiweb from libavl.w. */
/* libavl - library for manipulation of binary trees.
Copyright (C) 1998-2002, 2004 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
The author may be contacted at <blp@gnu.org> on the Internet, or
write to Ben Pfaff, Stanford University, Computer Science Dept., 353
Serra Mall, Stanford CA 94305, USA.
*/
#ifndef AVL_H
#define AVL_H 1
#include <stddef.h>
/* Function types. */
typedef int avl_comparison_func (const void *avl_a, const void *avl_b,
void *avl_param);
typedef void avl_item_func (void *avl_item, void *avl_param);
typedef void *avl_copy_func (void *avl_item, void *avl_param);
#ifndef LIBAVL_ALLOCATOR
#define LIBAVL_ALLOCATOR
/* Memory allocator. */
struct libavl_allocator
{
void *(*libavl_malloc) (struct libavl_allocator *, size_t libavl_size);
void (*libavl_free) (struct libavl_allocator *, void *libavl_block);
};
#endif
/* Default memory allocator. */
extern struct libavl_allocator avl_allocator_default;
void *avl_malloc (struct libavl_allocator *, size_t);
void avl_free (struct libavl_allocator *, void *);
/* Maximum AVL height. */
#ifndef AVL_MAX_HEIGHT
#define AVL_MAX_HEIGHT 32
#endif
/* Tree data structure. */
struct avl_table
{
struct avl_node *avl_root; /* Tree's root. */
avl_comparison_func *avl_compare; /* Comparison function. */
void *avl_param; /* Extra argument to |avl_compare|. */
struct libavl_allocator *avl_alloc; /* Memory allocator. */
size_t avl_count; /* Number of items in tree. */
unsigned long avl_generation; /* Generation number. */
};
/* An AVL tree node. */
struct avl_node
{
struct avl_node *avl_link[2]; /* Subtrees. */
void *avl_data; /* Pointer to data. */
signed char avl_balance; /* Balance factor. */
};
/* AVL traverser structure. */
struct avl_traverser
{
struct avl_table *avl_table; /* Tree being traversed. */
struct avl_node *avl_node; /* Current node in tree. */
struct avl_node *avl_stack[AVL_MAX_HEIGHT];
/* All the nodes above |avl_node|. */
size_t avl_height; /* Number of nodes in |avl_parent|. */
unsigned long avl_generation; /* Generation number. */
};
/* Table functions. */
struct avl_table *avl_create (avl_comparison_func *, void *,
struct libavl_allocator *);
struct avl_table *avl_copy (const struct avl_table *, avl_copy_func *,
avl_item_func *, struct libavl_allocator *);
void avl_destroy (struct avl_table *, avl_item_func *);
void **avl_probe (struct avl_table *, void *);
void *avl_insert (struct avl_table *, void *);
void *avl_replace (struct avl_table *, void *);
void *avl_delete (struct avl_table *, const void *);
void *avl_find (const struct avl_table *, const void *);
void avl_assert_insert (struct avl_table *, void *);
void *avl_assert_delete (struct avl_table *, void *);
#define avl_count(table) ((size_t) (table)->avl_count)
/* Table traverser functions. */
void avl_t_init (struct avl_traverser *, struct avl_table *);
void *avl_t_first (struct avl_traverser *, struct avl_table *);
void *avl_t_last (struct avl_traverser *, struct avl_table *);
void *avl_t_find (struct avl_traverser *, struct avl_table *, void *);
void *avl_t_insert (struct avl_traverser *, struct avl_table *, void *);
void *avl_t_copy (struct avl_traverser *, const struct avl_traverser *);
void *avl_t_next (struct avl_traverser *);
void *avl_t_prev (struct avl_traverser *);
void *avl_t_cur (struct avl_traverser *);
void *avl_t_replace (struct avl_traverser *, void *);
#endif /* avl.h */
源文件:
/* Produced by texiweb from libavl.w. */
/* libavl - library for manipulation of binary trees.
Copyright (C) 1998-2002, 2004 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
The author may be contacted at <blp@gnu.org> on the Internet, or
write to Ben Pfaff, Stanford University, Computer Science Dept., 353
Serra Mall, Stanford CA 94305, USA.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "avl.h"
/* Creates and returns a new table
with comparison function |compare| using parameter |param|
and memory allocator |allocator|.
Returns |NULL| if memory allocation failed. */
struct avl_table *
avl_create (avl_comparison_func *compare, void *param,
struct libavl_allocator *allocator)
{
struct avl_table *tree;
assert (compare != NULL);
if (allocator == NULL)
allocator = &avl_allocator_default;
tree = allocator->libavl_malloc (allocator, sizeof *tree);
if (tree == NULL)
return NULL;
tree->avl_root = NULL;
tree->avl_compare = compare;
tree->avl_param = param;
tree->avl_alloc = allocator;
tree->avl_count = 0;
tree->avl_generation = 0;
return tree;
}
/* Search |tree| for an item matching |item|, and return it if found.
Otherwise return |NULL|. */
void *
avl_find (const struct avl_table *tree, const void *item)
{
const struct avl_node *p;
assert (tree != NULL && item != NULL);
for (p = tree->avl_root; p != NULL; )
{
int cmp = tree->avl_compare (item, p->avl_data, tree->avl_param);
if (cmp < 0)
p = p->avl_link[0];
else if (cmp > 0)
p = p->avl_link[1];
else /* |cmp == 0| */
return p->avl_data;
}
return NULL;
}
/* Inserts |item| into |tree| and returns a pointer to |item|'s address.
If a duplicate item is found in the tree,
returns a pointer to the duplicate without inserting |item|.
Returns |NULL| in case of memory allocation failure. */
void **
avl_probe (struct avl_table *tree, void *item)
{
struct avl_node *y, *z; /* Top node to update balance factor, and parent. */
struct avl_node *p, *q; /* Iterator, and parent. */
struct avl_node *n; /* Newly inserted node. */
struct avl_node *w; /* New root of rebalanced subtree. */
int dir; /* Direction to descend. */
unsigned char da[AVL_MAX_HEIGHT]; /* Cached comparison results. */
int k = 0; /* Number of cached results. */
assert (tree != NULL && item != NULL);
z = (struct avl_node *) &tree->avl_root;
y = tree->avl_root;
dir = 0;
for (q = z, p = y; p != NULL; q = p, p = p->avl_link[dir])
{
int cmp = tree->avl_compare (item, p->avl_data, tree->avl_param);
if (cmp == 0)
return &p->avl_data;
if (p->avl_balance != 0) //找到将插入结点的最近非0的祖先
z = q, y = p, k = 0;
da[k++] = dir = cmp > 0;
}
//insert the item
n = q->avl_link[dir] =
tree->avl_alloc->libavl_malloc (tree->avl_alloc, sizeof *n);
//bad alloc
if (n == NULL)
return NULL;
tree->avl_count++;
n->avl_data = item;
n->avl_link[0] = n->avl_link[1] = NULL;
n->avl_balance = 0;
//this the first item be insert to the tree
if (y == NULL)
return &n->avl_data;
for (p = y, k = 0; p != n; p = p->avl_link[da[k]], k++)
if (da[k] == 0) //插入到本结点的左子树
p->avl_balance--;
else //插入到本结点的右子树
p->avl_balance++;
if (y->avl_balance == -2) //Y的左子树过高了
{
struct avl_node *x = y->avl_link[0];
if (x->avl_balance == -1)//左左
{
w = x;
y->avl_link[0] = x->avl_link[1];
x->avl_link[1] = y;
x->avl_balance = y->avl_balance = 0;
}
else //左右
{
assert (x->avl_balance == +1);
w = x->avl_link[1];
x->avl_link[1] = w->avl_link[0]; //进行左旋,3行
w->avl_link[0] = x;
y->avl_link[0] = w->avl_link[1];
w->avl_link[1] = y; //右旋
if (w->avl_balance == -1)
x->avl_balance = 0, y->avl_balance = +1;
else if (w->avl_balance == 0)
x->avl_balance = y->avl_balance = 0;
else /* |w->avl_balance == +1| */
x->avl_balance = -1, y->avl_balance = 0;
w->avl_balance = 0;
}
}
else if (y->avl_balance == +2) //Y的右子树过高了
{
struct avl_node *x = y->avl_link[1];
if (x->avl_balance == +1)
{
w = x;
y->avl_link[1] = x->avl_link[0];
x->avl_link[0] = y;
x->avl_balance = y->avl_balance = 0;
}
else
{
assert (x->avl_balance == -1);
w = x->avl_link[0];
x->avl_link[0] = w->avl_link[1];
w->avl_link[1] = x;
y->avl_link[1] = w->avl_link[0];
w->avl_link[0] = y;
if (w->avl_balance == +1)
x->avl_balance = 0, y->avl_balance = -1;
else if (w->avl_balance == 0)
x->avl_balance = y->avl_balance = 0;
else /* |w->avl_balance == -1| */
x->avl_balance = +1, y->avl_balance = 0;
w->avl_balance = 0;
}
}
else
return &n->avl_data;
z->avl_link[y != z->avl_link[0]] = w; //
tree->avl_generation++;
return &n->avl_data;
}
/* Inserts |item| into |table|.
Returns |NULL| if |item| was successfully inserted
or if a memory allocation error occurred.
Otherwise, returns the duplicate item. */
void *
avl_insert (struct avl_table *table, void *item)
{
void **p = avl_probe (table, item);
return p == NULL || *p == item ? NULL : *p;
}
/* Inserts |item| into |table|, replacing any duplicate item.
Returns |NULL| if |item| was inserted without replacing a duplicate,
or if a memory allocation error occurred.
Otherwise, returns the item that was replaced. */
void *
avl_replace (struct avl_table *table, void *item)
{
void **p = avl_probe (table, item);
if (p == NULL || *p == item)
return NULL;
else
{
void *r = *p;
*p = item;
return r;
}
}
/* Deletes from |tree| and returns an item matching |item|.
Returns a null pointer if no matching item found. */
void *
avl_delete (struct avl_table *tree, const void *item)
{
/* Stack of nodes. */
struct avl_node *pa[AVL_MAX_HEIGHT]; /* Nodes. */
unsigned char da[AVL_MAX_HEIGHT]; /* |avl_link[]| indexes. */
int k; /* Stack pointer. */
struct avl_node *p; /* Traverses tree to find node to delete. */
int cmp; /* Result of comparison between |item| and |p|. */
assert (tree != NULL && item != NULL);
k = 0;
p = (struct avl_node *) &tree->avl_root;
for (cmp = -1; cmp != 0;
cmp = tree->avl_compare (item, p->avl_data, tree->avl_param))
{
int dir = cmp > 0;
pa[k] = p;
da[k++] = dir;
p = p->avl_link[dir];
if (p == NULL)
return NULL;
}
item = p->avl_data;
if (p->avl_link[1] == NULL)
pa[k - 1]->avl_link[da[k - 1]] = p->avl_link[0];
else
{
struct avl_node *r = p->avl_link[1];
if (r->avl_link[0] == NULL)
{
r->avl_link[0] = p->avl_link[0];
r->avl_balance = p->avl_balance;
pa[k - 1]->avl_link[da[k - 1]] = r;
da[k] = 1;
pa[k++] = r;
}
else
{
struct avl_node *s;
int j = k++;
for (;;)
{
da[k] = 0;
pa[k++] = r;
s = r->avl_link[0];
if (s->avl_link[0] == NULL)
break;
r = s;
}
s->avl_link[0] = p->avl_link[0];
r->avl_link[0] = s->avl_link[1];
s->avl_link[1] = p->avl_link[1];
s->avl_balance = p->avl_balance;
pa[j - 1]->avl_link[da[j - 1]] = s;
da[j] = 1;
pa[j] = s;
}
}
tree->avl_alloc->libavl_free (tree->avl_alloc, p);
assert (k > 0);
while (--k > 0)
{
struct avl_node *y = pa[k];
if (da[k] == 0)
{
y->avl_balance++;
if (y->avl_balance == +1)
break;
else if (y->avl_balance == +2)
{
struct avl_node *x = y->avl_link[1];
if (x->avl_balance == -1)
{
struct avl_node *w;
assert (x->avl_balance == -1);
w = x->avl_link[0];
x->avl_link[0] = w->avl_link[1];
w->avl_link[1] = x;
y->avl_link[1] = w->avl_link[0];
w->avl_link[0] = y;
if (w->avl_balance == +1)
x->avl_balance = 0, y->avl_balance = -1;
else if (w->avl_balance == 0)
x->avl_balance = y->avl_balance = 0;
else /* |w->avl_balance == -1| */
x->avl_balance = +1, y->avl_balance = 0;
w->avl_balance = 0;
pa[k - 1]->avl_link[da[k - 1]] = w;
}
else
{
y->avl_link[1] = x->avl_link[0];
x->avl_link[0] = y;
pa[k - 1]->avl_link[da[k - 1]] = x;
if (x->avl_balance == 0)
{
x->avl_balance = -1;
y->avl_balance = +1;
break;
}
else
x->avl_balance = y->avl_balance = 0;
}
}
}
else
{
y->avl_balance--;
if (y->avl_balance == -1)
break;
else if (y->avl_balance == -2)
{
struct avl_node *x = y->avl_link[0];
if (x->avl_balance == +1)
{
struct avl_node *w;
assert (x->avl_balance == +1);
w = x->avl_link[1];
x->avl_link[1] = w->avl_link[0];
w->avl_link[0] = x;
y->avl_link[0] = w->avl_link[1];
w->avl_link[1] = y;
if (w->avl_balance == -1)
x->avl_balance = 0, y->avl_balance = +1;
else if (w->avl_balance == 0)
x->avl_balance = y->avl_balance = 0;
else /* |w->avl_balance == +1| */
x->avl_balance = -1, y->avl_balance = 0;
w->avl_balance = 0;
pa[k - 1]->avl_link[da[k - 1]] = w;
}
else
{
y->avl_link[0] = x->avl_link[1];
x->avl_link[1] = y;
pa[k - 1]->avl_link[da[k - 1]] = x;
if (x->avl_balance == 0)
{
x->avl_balance = +1;
y->avl_balance = -1;
break;
}
else
x->avl_balance = y->avl_balance = 0;
}
}
}
}
tree->avl_count--;
tree->avl_generation++;
return (void *) item;
}
/* Refreshes the stack of parent pointers in |trav|
and updates its generation number. */
static void
trav_refresh (struct avl_traverser *trav)
{
assert (trav != NULL);
trav->avl_generation = trav->avl_table->avl_generation;
if (trav->avl_node != NULL)
{
avl_comparison_func *cmp = trav->avl_table->avl_compare;
void *param = trav->avl_table->avl_param;
struct avl_node *node = trav->avl_node;
struct avl_node *i;
trav->avl_height = 0;
for (i = trav->avl_table->avl_root; i != node; )
{
assert (trav->avl_height < AVL_MAX_HEIGHT);
assert (i != NULL);
trav->avl_stack[trav->avl_height++] = i;
i = i->avl_link[cmp (node->avl_data, i->avl_data, param) > 0];
}
}
}
/* Initializes |trav| for use with |tree|
and selects the null node. */
void
avl_t_init (struct avl_traverser *trav, struct avl_table *tree)
{
trav->avl_table = tree;
trav->avl_node = NULL;
trav->avl_height = 0;
trav->avl_generation = tree->avl_generation;
}
/* Initializes |trav| for |tree|
and selects and returns a pointer to its least-valued item.
Returns |NULL| if |tree| contains no nodes. */
void *
avl_t_first (struct avl_traverser *trav, struct avl_table *tree)
{
struct avl_node *x;
assert (tree != NULL && trav != NULL);
trav->avl_table = tree;
trav->avl_height = 0;
trav->avl_generation = tree->avl_generation;
x = tree->avl_root;
if (x != NULL)
while (x->avl_link[0] != NULL)
{
assert (trav->avl_height < AVL_MAX_HEIGHT);
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[0];
}
trav->avl_node = x;
return x != NULL ? x->avl_data : NULL;
}
/* Initializes |trav| for |tree|
and selects and returns a pointer to its greatest-valued item.
Returns |NULL| if |tree| contains no nodes. */
void *
avl_t_last (struct avl_traverser *trav, struct avl_table *tree)
{
struct avl_node *x;
assert (tree != NULL && trav != NULL);
trav->avl_table = tree;
trav->avl_height = 0;
trav->avl_generation = tree->avl_generation;
x = tree->avl_root;
if (x != NULL)
while (x->avl_link[1] != NULL)
{
assert (trav->avl_height < AVL_MAX_HEIGHT);
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[1];
}
trav->avl_node = x;
return x != NULL ? x->avl_data : NULL;
}
/* Searches for |item| in |tree|.
If found, initializes |trav| to the item found and returns the item
as well.
If there is no matching item, initializes |trav| to the null item
and returns |NULL|. */
void *
avl_t_find (struct avl_traverser *trav, struct avl_table *tree, void *item)
{
struct avl_node *p, *q;
assert (trav != NULL && tree != NULL && item != NULL);
trav->avl_table = tree;
trav->avl_height = 0;
trav->avl_generation = tree->avl_generation;
for (p = tree->avl_root; p != NULL; p = q)
{
int cmp = tree->avl_compare (item, p->avl_data, tree->avl_param);
if (cmp < 0)
q = p->avl_link[0];
else if (cmp > 0)
q = p->avl_link[1];
else /* |cmp == 0| */
{
trav->avl_node = p;
return p->avl_data;
}
assert (trav->avl_height < AVL_MAX_HEIGHT);
trav->avl_stack[trav->avl_height++] = p;
}
trav->avl_height = 0;
trav->avl_node = NULL;
return NULL;
}
/* Attempts to insert |item| into |tree|.
If |item| is inserted successfully, it is returned and |trav| is
initialized to its location.
If a duplicate is found, it is returned and |trav| is initialized to
its location. No replacement of the item occurs.
If a memory allocation failure occurs, |NULL| is returned and |trav|
is initialized to the null item. */
void *
avl_t_insert (struct avl_traverser *trav, struct avl_table *tree, void *item)
{
void **p;
assert (trav != NULL && tree != NULL && item != NULL);
p = avl_probe (tree, item);
if (p != NULL)
{
trav->avl_table = tree;
trav->avl_node =
((struct avl_node *)
((char *) p - offsetof (struct avl_node, avl_data)));
trav->avl_generation = tree->avl_generation - 1;
return *p;
}
else
{
avl_t_init (trav, tree);
return NULL;
}
}
/* Initializes |trav| to have the same current node as |src|. */
void *
avl_t_copy (struct avl_traverser *trav, const struct avl_traverser *src)
{
assert (trav != NULL && src != NULL);
if (trav != src)
{
trav->avl_table = src->avl_table;
trav->avl_node = src->avl_node;
trav->avl_generation = src->avl_generation;
if (trav->avl_generation == trav->avl_table->avl_generation)
{
trav->avl_height = src->avl_height;
memcpy (trav->avl_stack, (const void *) src->avl_stack,
sizeof *trav->avl_stack * trav->avl_height);
}
}
return trav->avl_node != NULL ? trav->avl_node->avl_data : NULL;
}
/* Returns the next data item in inorder
within the tree being traversed with |trav|,
or if there are no more data items returns |NULL|. */
void *
avl_t_next (struct avl_traverser *trav)
{
struct avl_node *x;
assert (trav != NULL);
if (trav->avl_generation != trav->avl_table->avl_generation)
trav_refresh (trav);
x = trav->avl_node;
if (x == NULL)
{
return avl_t_first (trav, trav->avl_table);
}
else if (x->avl_link[1] != NULL)
{
assert (trav->avl_height < AVL_MAX_HEIGHT);
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[1];
while (x->avl_link[0] != NULL)
{
assert (trav->avl_height < AVL_MAX_HEIGHT);
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[0];
}
}
else
{
struct avl_node *y;
do
{
if (trav->avl_height == 0)
{
trav->avl_node = NULL;
return NULL;
}
y = x;
x = trav->avl_stack[--trav->avl_height];
}
while (y == x->avl_link[1]);
}
trav->avl_node = x;
return x->avl_data;
}
/* Returns the previous data item in inorder
within the tree being traversed with |trav|,
or if there are no more data items returns |NULL|. */
void *
avl_t_prev (struct avl_traverser *trav)
{
struct avl_node *x;
assert (trav != NULL);
if (trav->avl_generation != trav->avl_table->avl_generation)
trav_refresh (trav);
x = trav->avl_node;
if (x == NULL)
{
return avl_t_last (trav, trav->avl_table);
}
else if (x->avl_link[0] != NULL)
{
assert (trav->avl_height < AVL_MAX_HEIGHT);
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[0];
while (x->avl_link[1] != NULL)
{
assert (trav->avl_height < AVL_MAX_HEIGHT);
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[1];
}
}
else
{
struct avl_node *y;
do
{
if (trav->avl_height == 0)
{
trav->avl_node = NULL;
return NULL;
}
y = x;
x = trav->avl_stack[--trav->avl_height];
}
while (y == x->avl_link[0]);
}
trav->avl_node = x;
return x->avl_data;
}
/* Returns |trav|'s current item. */
void *
avl_t_cur (struct avl_traverser *trav)
{
assert (trav != NULL);
return trav->avl_node != NULL ? trav->avl_node->avl_data : NULL;
}
/* Replaces the current item in |trav| by |new| and returns the item replaced.
|trav| must not have the null item selected.
The new item must not upset the ordering of the tree. */
void *
avl_t_replace (struct avl_traverser *trav, void *new)
{
void *old;
assert (trav != NULL && trav->avl_node != NULL && new != NULL);
old = trav->avl_node->avl_data;
trav->avl_node->avl_data = new;
return old;
}
/* Destroys |new| with |avl_destroy (new, destroy)|,
first setting right links of nodes in |stack| within |new|
to null pointers to avoid touching uninitialized data. */
static void
copy_error_recovery (struct avl_node **stack, int height,
struct avl_table *new, avl_item_func *destroy)
{
assert (stack != NULL && height >= 0 && new != NULL);
for (; height > 2; height -= 2)
stack[height - 1]->avl_link[1] = NULL;
avl_destroy (new, destroy);
}
/* Copies |org| to a newly created tree, which is returned.
If |copy != NULL|, each data item in |org| is first passed to |copy|,
and the return values are inserted into the tree,
with |NULL| return values taken as indications of failure.
On failure, destroys the partially created new tree,
applying |destroy|, if non-null, to each item in the new tree so far,
and returns |NULL|.
If |allocator != NULL|, it is used for allocation in the new tree.
Otherwise, the same allocator used for |org| is used. */
struct avl_table *
avl_copy (const struct avl_table *org, avl_copy_func *copy,
avl_item_func *destroy, struct libavl_allocator *allocator)
{
struct avl_node *stack[2 * (AVL_MAX_HEIGHT + 1)];
int height = 0;
struct avl_table *new;
const struct avl_node *x;
struct avl_node *y;
assert (org != NULL);
new = avl_create (org->avl_compare, org->avl_param,
allocator != NULL ? allocator : org->avl_alloc);
if (new == NULL)
return NULL;
new->avl_count = org->avl_count;
if (new->avl_count == 0)
return new;
x = (const struct avl_node *) &org->avl_root;
y = (struct avl_node *) &new->avl_root;
for (;;)
{
while (x->avl_link[0] != NULL)
{
assert (height < 2 * (AVL_MAX_HEIGHT + 1));
y->avl_link[0] =
new->avl_alloc->libavl_malloc (new->avl_alloc,
sizeof *y->avl_link[0]);
if (y->avl_link[0] == NULL)
{
if (y != (struct avl_node *) &new->avl_root)
{
y->avl_data = NULL;
y->avl_link[1] = NULL;
}
copy_error_recovery (stack, height, new, destroy);
return NULL;
}
stack[height++] = (struct avl_node *) x;
stack[height++] = y;
x = x->avl_link[0];
y = y->avl_link[0];
}
y->avl_link[0] = NULL;
for (;;)
{
y->avl_balance = x->avl_balance;
if (copy == NULL)
y->avl_data = x->avl_data;
else
{
y->avl_data = copy (x->avl_data, org->avl_param);
if (y->avl_data == NULL)
{
y->avl_link[1] = NULL;
copy_error_recovery (stack, height, new, destroy);
return NULL;
}
}
if (x->avl_link[1] != NULL)
{
y->avl_link[1] =
new->avl_alloc->libavl_malloc (new->avl_alloc,
sizeof *y->avl_link[1]);
if (y->avl_link[1] == NULL)
{
copy_error_recovery (stack, height, new, destroy);
return NULL;
}
x = x->avl_link[1];
y = y->avl_link[1];
break;
}
else
y->avl_link[1] = NULL;
if (height <= 2)
return new;
y = stack[--height];
x = stack[--height];
}
}
}
/* Frees storage allocated for |tree|.
If |destroy != NULL|, applies it to each data item in inorder. */
void
avl_destroy (struct avl_table *tree, avl_item_func *destroy)
{
struct avl_node *p, *q;
assert (tree != NULL);
for (p = tree->avl_root; p != NULL; p = q)
if (p->avl_link[0] == NULL)
{
q = p->avl_link[1];
if (destroy != NULL && p->avl_data != NULL)
destroy (p->avl_data, tree->avl_param);
tree->avl_alloc->libavl_free (tree->avl_alloc, p);
}
else
{
q = p->avl_link[0];
p->avl_link[0] = q->avl_link[1];
q->avl_link[1] = p;
}
tree->avl_alloc->libavl_free (tree->avl_alloc, tree);
}
/* Allocates |size| bytes of space using |malloc()|.
Returns a null pointer if allocation fails. */
void *
avl_malloc (struct libavl_allocator *allocator, size_t size)
{
assert (allocator != NULL && size > 0);
return malloc (size);
}
/* Frees |block|. */
void
avl_free (struct libavl_allocator *allocator, void *block)
{
assert (allocator != NULL && block != NULL);
free (block);
}
/* Default memory allocator that uses |malloc()| and |free()|. */
struct libavl_allocator avl_allocator_default =
{
avl_malloc,
avl_free
};
#undef NDEBUG
#include <assert.h>
/* Asserts that |avl_insert()| succeeds at inserting |item| into |table|. */
void
(avl_assert_insert) (struct avl_table *table, void *item)
{
void **p = avl_probe (table, item);
assert (p != NULL && *p == item);
}
/* Asserts that |avl_delete()| really removes |item| from |table|,
and returns the removed item. */
void *
(avl_assert_delete) (struct avl_table *table, void *item)
{
void *p = avl_delete (table, item);
assert (p != NULL);
return p;
}
以上是C语言的实现。后面是本人写的 AVL tree的C++源代码模板(哪天补充上)。