這是我第一堂課的作業。它着重於c中的動態分配,以bst的形式。家庭作業,遞歸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」。如何打印該值,但仍然出現分段錯誤?
你不要你'newnode'附加到'insert_node'樹。 – michaelmeyer