【发布时间】:2017-12-30 08:16:30
【问题描述】:
我有一个任务是编写一个自平衡二叉搜索树。我决定使用 AVL 树,因为它是我们在课堂上讨论过的。然后使用给定的输入 { 3, 5, 61, 9, 32, 7, 1, 45, 26, 6} 我期待输出:
7
6-----|-----32
3----| 9----|----45
1---| |---26 |---61
也就是说,除非我严重误解并因此错误地计算了 AVL 树在平衡自身时应该做什么。我得到的输出完全不同:
5
3-----|-----61
1----| 9----|
7---|---32
6--| 26--|--45
再一次,除非我完全错了,否则那棵树是不平衡的。我用来设置树的函数是这样定义的:
node* insertKeyAVL(node* n, int e)
{
int cmpVal;
if (n == NULL){
n = create_node();
n->data = e;
} else if (e < n->data) {
if (n->left == NULL){
n->left = create_node();
n->left->data = e;
n->left->parent = n;
} else {
n->left = insertKeyAVL(n->left, e);
}
cmpVal = height(n->left) - height(n->right);
} else {
if (n->right == NULL){
n->right = create_node();
n->right->data = e;
n->right->parent = n;
} else {
n->right = insertKeyAVL(n->right, e);
}
cmpVal = height(n->right) - height(n->left);
}
if (cmpVal > 2){
if (n->left){
if (e < n->left->data)
n = rotate_left(n);
else
n = rotate_right_left(n);
} else if (n->right){
if (e > n->right->data)
n = rotate_right(n);
else
n = rotate_left_right(n);
}
}
n->height = max(height(n->left), height(n->right)) + 1;
return n;
}
我用来存储所有数据的结构是这样定义的:
typedef struct node
{
struct node *parent;
struct node* left;
struct node* right;
int data;
int height;
} node;
函数 rotate_left_right 和 rotate_right_left 是旋转第一个 post-fix 然后第二个 post-fix 方向的基本函数,它们各自的方向都依赖于 rotate_left 和 rotate_right。向左旋转定义如下:
node* rotate_left(node* n)
{
node* tmp = n->left;
n->left = tmp->right;
tmp->right = n;
tmp->parent = n->parent;
n->parent = tmp;
n->height = max(height(n->left), height(n->right)) + 1;
tmp->height = max(height(tmp->left), n->height) + 1;
return tmp;
}
rotate_right 类似,但调整为向右旋转。
我想知道这段代码在哪里搞砸了,所以它不会产生所需的输出。
【问题讨论】:
-
你的“应该”树完全丢失了 26 个。
-
你是对的,感谢现在修复它
-
您可能会从C AVL tree、AVL tree Wikipedia 和github containers 的评论中受益