我的二叉樹設定如下:
`
我也像這樣初始化 BT 的第一個節點:
`
到目前為止一切正常。但是,當我嘗試插入我的 BT 時,我不斷出現意外行為。我的插入函式看起來像這樣。
`
但是,當我從 main 函式運行代碼并嘗試插入到 BT 中時,第一個節點顯示得很好,但第二個節點變成了一些大而奇怪的數字。當我在除錯器中運行它時,它顯示了我期望的數字,但這不是列印出來的數字。這是我的主要方法。
`
問題出在我的插入函式中,但我不確定出了什么問題,因為當我通過除錯器運行它時,我得到了 5 和 6 的預期值。
uj5u.com熱心網友回復:
在這些宣告中
struct Node* node1 = (struct Node*) malloc(sizeof(struct Node*));
^^^^^^^^^^^^
struct Node* node2 = (struct Node*) malloc(sizeof(struct Node*));
^^^^^^^^^^^^
您分配的記憶體不正確。而是寫
struct Node* node1 = (struct Node*) malloc(sizeof(struct Node));
^^^^^^^^^^^
struct Node* node2 = (struct Node*) malloc(sizeof(struct Node));
^^^^^^^^^^^^
函式中也存在同樣的問題insert。
同樣在函式內將 return 陳述句移動到函式的末尾
struct Node* insert(struct Node* rootPtr, struct Node* node) {
if (rootPtr == NULL) {
rootPtr = (struct Node*) malloc(sizeof(struct Node));
rootPtr->data = node->data;
rootPtr->left = NULL;
rootPtr->right = NULL;
}
if (rootPtr->data > node->data) {
rootPtr->left = insert(rootPtr->left, node);
} else if (rootPtr->data < node->data) {
rootPtr->right = insert(rootPtr->right, node);
}
return rootPtr;
}
請注意將指標傳遞給整個節點,因為第二個引數效率低下且容易出錯。你可以只傳遞一個整數。所以函式應該宣告為
struct Node* insert(struct Node* rootPtr, int data );
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328815.html
