gpt4 book ai didi

c - 插入 AVL 树 : segmentation fault error

转载 作者:太空宇宙 更新时间:2023-11-03 23:37:14 24 4
gpt4 key购买 nike

我制作了 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 时,我只插入了 1 个数字当我在 Linux 中运行它时,出现段错误(核心已转储)

我该如何解决这个问题?谢谢

最佳答案

你在这里犯了一个错误:

static NODE *_insert(NODE *root, NODE *newPtr)
{
if (root) return newPtr;

当没有根(即空树)时,新树仅由新节点组成。因此,这应该是:

    if (!root) return newPtr;

这意味着,您的段错误发生在下一行:

if (newPtr->data < root->data)

因为您在此处取消引用空指针 root

关于c - 插入 AVL 树 : segmentation fault error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56423166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com