[英]Homework, Recursive BST insert function in C
這是我上c課的第一堂課。 它專注於以bst形式在c中進行動態分配。
我必須有一個動態分配的BST,以遞歸方式實現。 我知道遍歷正常,並且在插入節點時遇到問題。 我只有根節點,而每個其他節點似乎都設置為NULL。 我認為遍歷時無法打印其余節點,因為我正在嘗試訪問NULL結構的數據成員。 到目前為止,我的代碼如下:
void insert_node(TreeNode** root, int toInsert){
if(*root==NULL){
TreeNode *newnode = (TreeNode *)malloc(sizeof(TreeNode));
newnode->data = toInsert;
newnode->left = NULL;
newnode->right = NULL;
}
else if(toInsert > (*root)->data){ //if toInsert greater than current
struct TreeNode **temp = (TreeNode **)malloc(sizeof(struct TreeNode*));
*temp = (*root)->right;
insert_node(temp, toInsert);
}
else{ //if toInsert is less than or equal to current
struct TreeNode **temp = (TreeNode **)malloc(sizeof(struct TreeNode*));
*temp = (*root)->left;
insert_node(temp, toInsert);
}
}
void build_tree(TreeNode** root, const int elements[], const int count){
if(count > 0){
TreeNode *newroot = (TreeNode *)malloc(sizeof(TreeNode));
newroot->data = elements[0];
newroot->left = NULL;
newroot->right = NULL;
*root = newroot;
for(int i = 1; i < count; i++){
insert_node(root, elements[i]);
}
}
我確定這只是許多問題之一,但是在使用“(* root)-> data”的任何行上都會出現分段錯誤,我不確定為什么。
附帶說明一下,盡管在“(* root)-> data”行中遇到分段錯誤,但我仍然能夠打印“(* root)-> data”。 如何打印該值,但仍然出現分段錯誤?
太亂了 有些事情可能會有所幫助
1)不需要使用TreeNode * (指向指針的指針)作為參數。 使用jsut TreeNode 。 (這里出錯了,因為它是文本編輯器的某些功能,請考慮在此行中的每個TreeNode之后加上*)
2)不是嚴格的規則,但是作為最佳實踐,請避免使用鏈接列表的第一個節點來存儲實際值。 僅用作列表的標題。 原因是,如果您需要刪除此節點,則不會丟失列表。 只是一個提示
3)在您的第一個函數中,如果* root == NULL,我寧願使函數失敗,也不願將其添加到臨時列表中(該函數在當前代碼中丟失了,請參見將值添加到不是被傳遞到函數之外。
4)好吧,實際上,如果新值大於節點,則實際上使它移到右邊,如果新值小於節點,則使它移到左邊,但是它永遠不會停止。 參見以下示例:假設您具有列表1-> 3-> 4。 現在您要插入2。該算法將執行什么操作? 繼續嘗試在1節點和3節點中插入,在它們之間切換,但不要實際插入任何東西。 解決方案:在自底向上構建此列表時,將始終對列表進行排序(如果您正確插入了節點)。 因此,您只需要檢查下一個節點是否更高,如果更高,請在您要插入的位置正確插入。
5)如果要傳遞TreeNode * root作為參數(在第二個函數上),則不必重新創建新列表並使root = newlist。 只需使用根即可。 所有這些都會導致(未測試,可能有一些錯誤):
void insert_node(TreeNode* root, int toInsert){
if(root==NULL){
printf("Error");
return;
}
TreeNode* temp = root; //I just don't like to mess with the original list, rather do this
if(temp->right!=NULL && toInsert > temp->right->data){ //if toInsert greater than next
insert_node(temp->right, toInsert);
}
else{ //if toInsert is less or equal than next node
TreeNode* temp2 = temp->right; //grabbing the list after this node
temp->right=(TreeNode*)malloc(sizeof(TreeNode)); //making room for the new node
temp->right->right=temp2; //putting the pointer to the right position
temp->right->left=temp; //setting the left of the next node to the current
temp->right->data=toInsert;
}
}
void build_tree(TreeNode* root, const int elements[], const int count){
if(count > 0){
for(int i = 0; i < count; i++){
insert_node(root, elements[i]);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.