[問題] 二元搜索樹加資料的問題

作者: Chieng9086 (chieng9086)   2016-05-25 18:17:57
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
當我輸入的整數資料,若下一筆資料小於前面某幾筆,會出現存取違規
餵入的資料(Input):
EX:15 20 10(10這筆就會造成存取違規)
預期的正確結果(Expected Output):
15 20 10 可以很任意打入大小順序隨意的數
錯誤結果(Wrong Output):
擲回例外狀況: 讀取存取違規。
current 為 nullptr。
程式碼(Code):(請善用置底文網頁, 記得排版)
// 二元數樹結構
struct B_tree {
int data;
struct B_tree *Llink;
struct B_tree *Rlink;
};
typedef struct B_tree node;
node *root; //樹根
// 將資料加入二元搜索樹
node *tree_Insert(node *root, int value) {
node *new_node;
node *current;
node *parent;
new_node = (node *)malloc(sizeof(node));
new_node->data = value;
new_node->Llink = NULL;
new_node->Rlink = NULL;
if (root == NULL)
{
return new_node;
}
else
{
current = root;
while (current != NULL)
{
parent = current;
if (current->data > value)
current = current->Llink;
else
current = current->Rlink;
}
if (parent->data > value)
parent->Llink = new_node;
else
parent->Rlink = new_node;
}
return root;
}
補充說明(Supplement):
出問題時,Visual Studio下面這行都會有箭頭
current = current->Llink;
作者: opl164 (opl)   2016-05-26 09:33:00
你的左右子葉都是NULL?
作者: KJFC (磁鐵貓)   2016-05-26 10:15:00
學用遞迴加點吧 好用不容易出錯
作者: leo850319 (不要說話)   2016-05-26 12:51:00
你的current會一直指到null還沒加下一個點 你就往下指了

Links booklink

Contact Us: admin [ a t ] ucptt.com