我试图遍历树的级别顺序,但是我的数字不是按级别顺序排列,每隔一次我编译我的代码时都会出现错误:线程1:EXC_BAD_ACCESS(code = EXC_I386_GPFLT)
我在printf(“%d”,current-> val)处遇到错误;在我的代码行。
void printBreadthFirstTree(struct AVLTree *tree){
struct AVLnode **queue;
struct AVLnode *current = tree->root;
int start = 0;
int end = 0;
queue = (struct AVLnode **) malloc(100*sizeof(struct AVLnode));
while (current)
{
printf("%d ", current->val);
if (current->left){
queue[end] = current->left;
end++;
}
if (current->right){
queue[end] = current->right;
end++;
}
start++;
current = queue[start - 1];
}
}
我的树:
struct AVLnode * AVLnodeAdd(struct AVLnode * current, int newValue)
{
if(current == 0){
struct AVLnode* node = (struct AVLnode*) malloc(sizeof(struct AVLnode));
node->val = newValue;
node->left = 0;
node->right = 0;
node->height = 1;
return node;
}
else {
if (LT(newValue, current->val))
current->left = AVLnodeAdd(current->left, newValue);
else {
current->right = AVLnodeAdd(current->right, newValue);
}
}
return _balance(current);
}
我用于平衡树的代码:
struct AVLnode * _balance(struct AVLnode * current)
{
int cbf = bf(current);
if (cbf < -1) {
int drotation = h(current->left->right) - h(current->left->left);
if (drotation > 0){
current->left = rotateLeft(current->left);
}
return rotateRight(current);
} else if (cbf > 1) {
int drotation = h(current->right->right) - h(current->right->left);
if (drotation < 0) {
current->right = rotateRight(current->right);
}
return rotateLeft(current);
}
setHeight(current);
return current;
}
bf()只是通过从右侧减去左侧节点的高度来获得平衡因子。
实际上向该树添加值的主要代码是从输入文件运行的,而在主要方面,我有:
while((fscanf(file, "%i", &num)) != EOF){
addAVLTree(tree, num);
}
添加AVL树:
void addAVLTree(struct AVLTree *tree, TYPE val)
{
printf("%d ", val);
tree->root = AVLnodeAdd(tree->root, val);
tree->cnt++;
}
我应该得到以下输出:21 11 31 7 13 23 42 5 9 12 16 22 27 40 73 2 6 8 10 20 25 30 34 41 50 75 0 4 43 61 74
相反,我得到:27 13 40 8 21 31 50 5 11 20 23 30 34 42 73 2 7 10 12 16 22 25 41 43 61 74 0 4 6 9 75 1103571808 -9075224