简体   繁体   English

AVL /二进制搜索树

[英]AVL / Binary Search Tree

I have a C programming question. 我有一个C编程问题。 The below is a insert to a node with a key. 以下是带有密钥的节点的插入。

I don't understand why node->left = insert(node->left,key) 我不明白为什么node->left = insert(node->left,key)

I assume this code WILL update the node->left with what? 我假设这段代码将用什么来更新node->left

Isn't it calling insert() again? 它不是再次调用insert()吗? It's like calling the same function again and again isn't it a infinite loop or insert calling? 就像一次又一次地调用相同的函数,这不是无限循环还是插入调用?

I checked a few example, they are all updating the node->left that way by calling the same function again? 我检查了几个示例,它们都通过再次调用同一函数来更新node->left Let's say I misunderstood, what are the storing in it? 假设我误会了,其中存储了什么? The pointer? 指针? Or are they just magically linked? 还是它们只是神奇地联系在一起?

// An AVL tree node
struct node
{
    int key;
    struct node *left;
    struct node *right;
    int height;
};

struct node* insert(struct node* node, int key)
{
    /* 1.  Perform the normal BST rotation */
    if (node == NULL)
        return(newNode(key));

    if (key < node->key)
        node->left  = insert(node->left, key);//This just called Insert function again?
    else
        node->right = insert(node->right, key);

Yes, they are calling the insert function again, but note that the arguments have changed 1 . 是的,他们再次调用insert函数,但是请注意,参数已更改1 This is what is called recursion . 这就是所谓的递归

Also note that it does not always call the same function again: in case node==NULL it does not call it. 还要注意,它并不总是再次调用相同的函数:在node==NULL情况下,它不会调用它。 So this is not infinite; 所以这不是无限的。 as you take node->left , node->left->left and so one, you once come to a point where the pointer is NULL . 当您使用node->leftnode->left->left等时,您一次到达了指针为NULL的点。


1 I don't say that recursive call must always change its arguments, but that's the most common approach. 1我并不是说递归调用必须始终更改其参数,但这是最常见的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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