我制作了avl树,它可以成功编译。但是,在插入时,它仅插入1个数字并造成分段错误。我需要在哪里更改才能使代码成功?
我从此文件中获得了帮助 https://www.geeksforgeeks.org/avl-tree-set-1-insertion/ 并使静态内部函数_insert使代码看起来更简单。
/* internal function
This function uses recursion to insert the new data into a leaf node
return pointer to new root
*/
static NODE *_insert(NODE *root, NODE *newPtr)
{
if (root) return newPtr;
if (newPtr->data < root->data)
root->left = _insert(root->left, newPtr);
else if (newPtr->data >= root->data)
root->right = _insert(root->right, newPtr);
root->height = 1 + max(root->left->height, root->right->height);
int bal = getHeight(root);
if (bal > 1 && newPtr->data < root->left->data)
return rotateRight(root);
if (bal<-1 && newPtr->data > root->right->data)
return rotateLeft(root);
if (bal > 1 && newPtr->data > root->left->data)
{
root->left = rotateLeft(root->left);
return rotateRight(root);
}
if (bal < -1 && newPtr->data < root->right->data)
{
root->right = rotateRight(root->right);
return rotateLeft(root);
}
return root;
}
int AVL_Insert(AVL_TREE *pTree, int data)
{
NODE *pNode = _makeNode(data);
if (!pNode) return 0;
pTree->root = _insert(pTree->root, pNode);
if (!pTree->root) return 0;
else return 1;
}
``````
````````````
/* internal function
Exchanges pointers to rotate the tree to the right
updates heights of the nodes
return new root
*/
static NODE *rotateRight(NODE *root)
{
NODE *t1 = root->left;
NODE *t2 = t1->right;
t1->right = root;
root->left = t2;
root->height = max(root->left->height, root->right->height) + 1;
t1->height = max(t1->left->height, t1->right->height) + 1;
return t1;
}
/* internal function
Exchanges pointers to rotate the tree to the left
updates heights of the nodes
return new root
*/
static NODE *rotateLeft(NODE *root)
{
NODE *t1 = root->right;
NODE *t2 = t1->left;
t1->left = root;
root->right = t2;
root->height = max(root->left->height, root->right->height) + 1;
t1->height = max(t1->left->height, t1->right->height) + 1;
}
//main code
srand(time(NULL));
for (int i = 0; i < MAX_ELEM; i++)
{
data = rand() % (MAX_ELEM * 3) + 1; // random number
// data = i+1; // sequential number
fprintf(stdout, "%d ", data);
// insert function call
AVL_Insert(tree, data);
}
fprintf(stdout, "\n");
当我运行Visual Studio时,我只插入了一个数字 当我在linux中运行时,出现分段错误(核心已转储)
我该如何解决?谢谢
答案 0 :(得分:1)
您在这里犯了一个错误:
static NODE *_insert(NODE *root, NODE *newPtr)
{
if (root) return newPtr;
如果没有 根(即空树),则新树仅由新节点组成。因此,应为:
if (!root) return newPtr;
这意味着您的细分错误发生在下一行:
if (newPtr->data < root->data)
因为您在此处取消引用了空指针root
。