[英]C Binary Search Tree Insertion Pointer Issue
我正在嘗試實現二進制搜索樹插入,但是遇到了問題。
我已經使用以下Node和Tree結構實現了樹
typedef struct Node {
double value;
struct Node *parent;
struct Node *right_child;
struct Node *left_child;
} Node;
typedef struct Tree {
struct Node *root;
} Tree;
以下是插入功能
void insert(Tree *t, Node n) {
Node *x = t->root, *y = NULL;
//follow tree down until we reach a leaf of the tree
while (x != NULL) {
//save last non-NULL value. We will insert node n as a child to this leaf.
y = x;
if (n.value < x->value) {
x = x->left_child;
} else {
x = x->right_child;
}
}
//The parent of the node to insert is the leaf we reached
n.parent = y;
//If n is greater than y then it is its right child and vice-versa.
if (n.value > y->value) {
y->right_child = &n;
} else {
y->left_child = &n;
}
}
當我在主要方法中運行此命令時
int main(void) {
Node n1;
Node n2;
Node n3;
n1.value = 4;
n1.parent = NULL;
n1.left_child = NULL;
n1.right_child = NULL;
n2.value = 2;
n2.parent = NULL;
n2.left_child = NULL;
n2.right_child = NULL;
n3.value = 1;
n3.parent = NULL;
n3.left_child = NULL;
n3.right_child = NULL;
Tree t;
t.root = &n1;
insert(&t,n2);
insert(&t,n3);
printf("n1 left child %f \n", n1.left_child->value);
return EXIT_SUCCESS;
}
它打印n1 left child 1.000000
,這是不正確的。 應該是2。我嘗試插入打印語句進行調試,並且似乎insert
函數在最后將子代分配給錯誤的指針(即, n2
節點在插入后不再持久)。 所以我認為這意味着y
。 我不認為y
表示我想要的是指向樹中葉子節點的指針(我將在其中插入新節點n)。
您正在使用一個臨時變量的地址,並在釋放該變量后對其取消引用,這意味着您的程序將調用未定義的行為 。 在
void insert(Tree *t, Node n)
Node n
參數分配在insert()
函數的堆棧框架中,當該函數返回時,該框架將被破壞,導致n
被釋放。
您在Tree *t;
持有指向其地址的指針Tree *t;
,函數返回后訪問該指針無效。
您必須從main()
傳遞一個指向n2
和n3
地址的指針,像這樣
insert(&t, &n2);
insert(&t, &n3);
並更改insert()
以直接接受指針,而不是實例的本地副本。
使用我建議的解決方案, n2
和n3
分配在main()
的堆棧幀內,因此其生命周期等於整個程序的生命周期,因為您將傳遞它們的地址,指向樹中節點的指針仍將指向有效內存在insert()
返回之后,您將能夠打印其內容而無需調用未定義的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.