Я пытаюсь пересмотреть порядок уровней дерева, но мои числа не соответствуют порядку уровней, и каждый раз, когда я компилирую код, я получаю сообщение об ошибке: Поток 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 Tree:
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