繁体   English   中英

如何在 C 的二叉搜索树数据结构中使用双指针?

[英]How to use double pointers in binary search tree data structure in C?

我正在努力在 C 中实现二叉搜索树数据结构,但我卡在了指向左子或右子的部分。 我知道如果您插入的值小于根,如果它更大,它会向左和向右。 我只是在为双指针部分苦苦挣扎,如下面的代码所示。 让我们以bs_tree_insert_left为例,我希望pos->left_child指向left_child以便将给定的值放在那里,但我不确定我会如何写这个。 关于主要 function 的上下文, arr[]中的数字将随机打乱,但我删除了这部分代码以保持帖子简短紧凑。

struct node
{
    int value;
    struct node *left_child;
    struct node *right_child;
};

typedef struct node BSTree;
typedef struct node* BSTreePos;

BSTree *bs_tree_make(int value){
  // Allocate memory for new node
  struct node* origin = (struct node*)malloc(sizeof(struct node));
  // Assign data to this node
 origin->value = value;

 // Initialize left and
 // right children as NULL
 origin->left_child = NULL;
 origin->right_child = NULL;
 return (origin);
}

BSTreePos bs_tree_insert_left(int value, BSTreePos pos){
  
  pos->left_child = bs_tree_make(value);
  return pos->left_child;
}
void insert_value(int value, BSTreePos pos)
{
  if (pos == NULL) return bs_tree_make(value);
  if (value < pos->value)
  {
  pos->left_child = bs_tree_insert_left(value, pos->left_child);
  }
  else if (value > pos->value)
  {
  pos->right_child = bs_tree_insert_right(value, pos->right_child);
  }

}

int main(void)
{
    // Create an array with the values 1, 2, ..., 10 and print out the content.
    int n = 10;
    int arr[n];

for (int i = 0 ; i < n ; i++) {
    arr[i] = i + 1;
}

print_array(n, arr);
BSTree *tree = bs_tree_make(arr[0]);
for (int i = 1 ; i < n ; i++) {
    BSTreePos pos = bs_tree_root(tree);
    insert_value(arr[i], pos);
}
return 0;

}

你知道吗,我只是要编写正确的算法,使用双指针达到最大效果。

void insert_value(int value, struct node **node)
{
    if (*node == NULL) {
        *node = malloc(sizeof(struct node));
        node[0]->value = value;
        node[0]->left_child = NULL;
        node[0]->right_child = NULL;
    } else if (node[0]->value < value)
        insert_value(value, &node[0]->left_child);
    else if (node[0]-> value > value)
        insert_value(value, &node[0]->right_child);
    /* else duplicate value found -- don't insert (from OP's code) */
}


    BSTree *tree = NULL;
    for (int i = 0 ; i < n ; i++) {
        insert_value(arr[i], &tree);
    }

node[0]->value是通过双指针访问结构的惯用方式。

但是让我们看看它是如何工作的,以及它从双指针中获得了多少价值。 空树存储为NULL指针。 这使得初始化树并将节点添加到树中的代码相同。 请注意insert_value如何使用指向树的双指针; 这允许它在添加第一个节点或其任何子节点时填写根节点。 因此,作为指针的指针的双指针用于在我们创建新节点时更新指向节点的指针。

使用此算法,具有bs_tree_insert_left从字面上看是没有意义的。 整个想法是执行插入的代码不知道它在哪里插入节点。

有趣的事实:编译器会在使用优化编译时为我们转换递归。

暂无
暂无

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

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