【发布时间】:2019-10-18 18:15:54
【问题描述】:
我制作了 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 中运行它时,我得到分段错误(核心转储)
我该如何解决这个问题?谢谢
【问题讨论】:
-
我没有看到
tree或AVL_tree在任何地方声明。请修复 minimal reproducible example 并使用调试器查找段错误的确切行。 -
并且不要使用下划线开头的标识符。这是不好的做法。
标签: c recursion avl-tree insertion