c - 无法理解二叉搜索树中插入的逻辑

标签 c data-structures binary-search-tree

我正在研究二叉搜索树,我通过了这段我无法理解的代码

//head为根节点&num为关键元素

void generate(struct node **head, int num)
{
    struct node *temp = *head, *prev = *head;
    if (*head == NULL)
    {
        *head = (struct node *)malloc(sizeof(struct node));
        (*head)->a = num;
        (*head)->left = (*head)->right = NULL;
    }
    else
    {
        while (temp != NULL)
        {
            if (num > temp->a)
            {
                prev = temp;
                temp = temp->right;
            }
            else
            {
                prev = temp;
                temp = temp->left;
            }
        }
        temp = (struct node *)malloc(sizeof(struct node));
        temp->a = num;

//我无法理解以下几行

        if (num >= prev->a)
        {
            prev->right = temp;
        }
        else
        {
            prev->left = temp;
        }
    }

}

最佳答案

在二叉搜索树中,左子节点的值低于父节点,右子节点的值高于父节点。那么,如果你想插入一个新的节点,你就必须找到他的站点。当树的节点值小于您的 num 时,您将树导航到右侧。当一个节点的值高于您的 num 时,您将树导航到左侧,而不是右侧。这是循环,直到到达 NULL 节点,该节点将是值为 num 的新节点的位置。

关于c - 无法理解二叉搜索树中插入的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878207/

相关文章:

java - 该算法查找 Anagrams 的时间复杂度和空间复杂度是多少?

data-structures - 了解嵌套结构

java - 二叉搜索树递归插入不显示任何内容

C- 具有分配字符的结构 *

C 程序读取 ascii 文本文件但输出是 ISO-8859

c - 函数返回局部变量的地址,在c中

c - 为什么这个搜索函数返回一个指向指针的指针呢?

c - 如何获取从 shell 调用的二进制文件的文本段的基地址?

algorithm - 生成随机函数(不是数字!)——如何实现

C 二叉搜索树插入