[英]AVL Tree Insertion changes the root
I have to implement an AVL Tree in C.我必须在 C 中实现一个 AVL 树。 I wrote the following insert-Method, but it only keeps changing the root of the tree.我编写了以下插入方法,但它只会不断更改树的根。
I think it has something to do with how I go through the tree.我认为这与我如何通过树 go 有关。 I know how to do it when only a node is needed for the function, but how do I do it with an entire tree?当 function 只需要一个节点时,我知道该怎么做,但是如何处理整个树呢?
void AVL_insert(AVLTree* avlt, int value){
AVLTree *tree = avlt;
AVLNode *root = avlt->root;
if(tree->root == NULL){
AVLNode *node = calloc(1, sizeof(AVLNode));
node->value = value;
node->height = 0;
tree->root = node;
tree->numberOfNodes = avlt->numberOfNodes+1;
return;
}
else if(value < tree->root->value){
tree->root = root->left;
AVL_insert_value(tree, value);
}
else if(value > tree->root->value){
tree->root = root->right;
AVL_insert_value(tree, value);
}
else return;
//..add height, balance tree
}
Structs:结构:
struct AVLNode{
struct AVLNode* left;
struct AVLNode* right;
struct AVLNode* parent;
int value;
int height;
};
struct AVLTree{
struct AVLNode* root;
int numberOfNodes;
};
typedef struct AVLNode AVLNode;
typedef struct AVLTree AVLTree;
My guess what is wrong.我猜出了什么问题。
AVLNode *node = calloc(1, sizeof(AVLNode));
calloc()
set the content of the node to zeros. calloc()
将节点的内容设置为零。
tree->root = root->left; // root->left is `NULL`
Now, the root is NULL.现在,根是 NULL。
As result a new value is alternately added to either empty or 1-element tree.结果,一个新值会交替添加到空树或 1 元素树中。
Possible fix: Do not update root's children.可能的修复:不要更新根的孩子。 Just insert a value into the tree as leaf and let re-balancing code optimize tree's depth while returning from recursion.只需将一个值作为叶子插入树中,然后让重新平衡代码在从递归返回时优化树的深度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.