简体   繁体   English

AVL 树插入更改根

[英]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.我猜出了什么问题。

  1. Inserting to an empty node allocates the root, it's left and right children are set to NULL.插入一个空节点分配根,它的左右孩子设置为NULL。
AVLNode *node = calloc(1, sizeof(AVLNode));

calloc() set the content of the node to zeros. calloc()将节点的内容设置为零。

  1. A new value is inserted.插入一个新值。 As a child is updated before recursion, the root is set to its left or right child.当一个孩子在递归之前被更新时,根被设置为它的左孩子或右孩子。 Both of them are NULL.它们都是 NULL。
tree->root = root->left; // root->left is `NULL`

Now, the root is NULL.现在,根是 NULL。

  1. Adding a next value.添加下一个值。 The root is NULL.根是 NULL。 Go to point 1. Go 到点 1。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM