[英]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.