[英]AVL Tree Insertion changes the root
我必須在 C 中實現一個 AVL 樹。 我編寫了以下插入方法,但它只會不斷更改樹的根。
我認為這與我如何通過樹 go 有關。 當 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
}
結構:
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;
我猜出了什么問題。
AVLNode *node = calloc(1, sizeof(AVLNode));
calloc()
將節點的內容設置為零。
tree->root = root->left; // root->left is `NULL`
現在,根是 NULL。
結果,一個新值會交替添加到空樹或 1 元素樹中。
可能的修復:不要更新根的孩子。 只需將一個值作為葉子插入樹中,然后讓重新平衡代碼在從遞歸返回時優化樹的深度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.