2016-11-04 53 views
-2

在這裏,我寫了一個代碼來實現二進制搜索tree.it不給任何錯誤,同時插入根node.But每當我試圖插入子節點,我得到以下警告程序崩潰,而在二叉搜索樹插入第二個節點

傳遞推兼容的指針類型的參數1

預期結構節點**但參數是結構節點*

傳遞推兼容的指針類型的參數1的

,然後程序crashes.What可能出錯,這代碼?

#include<stdio.h> 
struct node { 

    int data; 
    struct node *left; 
    struct node *right; 
}; 
void insert(int value); 
void push(struct node **root_node,struct node *newNode); 
void search(struct node *root_node,int value); 

struct node *root; 
int main(){ 
    root= NULL; 
    int option,value; 
    for(;;){ 
     printf("Please select an option from below : \n"); 
     printf("1 for insert\n"); 
     printf("2 for search\n"); 
     printf("please enter your option : "); 
     scanf("%d",&option); 
     printf("\n"); 
     switch(option){ 
      case 1: 
       printf("you choose to insert\n"); 
       printf("input your value :"); 
       scanf("%d",&value); 
       insert(value); 
       printf("\n"); 
       break; 

      default: 
       break; 

     } 
    } 
} 

void insert(int value){ 
    struct node newNode ; 

    newNode.data = value; 
    newNode.left = NULL; 
    newNode.right = NULL; 


    push(&root,&newNode); 

} 
void push(struct node **root_node,struct node *newNode){ 

    if(*root_node==NULL){ 
     *root_node = newNode; 
     printf("inserted\n\n\n"); 
    }else{ 
     if((*root_node)->data > newNode->data){ 
       push((*root_node)->left,newNode); 
       printf("left\n"); 
     }else{ 
      push((*root_node)->right,newNode); 
      printf("right\n"); 
     } 

    } 

} 
+2

1) 'struct node newNode;':'newNode'的生命週期在本地範圍內。 2)'push((* root_node) - > left,newNode);' - >'push(&(* root_node) - > left,newNode);' – BLUEPIXY

回答

0
struct node* search(struct node* root, int key) 
{ 
    // Base Cases: root is null or key is present at root 
    if (root == NULL || root->key == key) 
     return root; 

    // Key is greater than root's key 
    if (root->key < key) 
     return search(root->right, key); 

    // Key is smaller than root's key 
    return search(root->left, key); 
} 
+0

歡迎來到Stack Overflow。這是很好的代碼,但它與爲什麼'insert()'操作失敗的問題並沒有密切關係。 –

2

問題是這種類型的線路:

push((*root_node)->left,newNode); 

(*root_node)->leftstruct node*但你的函數需要struct node**(雙指針)。因此,你需要像一個變化:

push(&((*root_node)->left),newNode); 
    ^
    Notice 

除此之外,你不能把局部變量的樹,你在這裏做的:

void insert(int value){ 
    struct node newNode ; // Local variable 

使用malloc代替

void insert(int value){ 
    struct node* newNode = malloc(sizeof(struct node)); 
+0

爲什麼我不能把局部變量tree..i正在使用指針指向it..can請你解釋 –

+1

局部變量丟失(又名超出範圍),當函數返回所以你的指針會指向一些「無效的」內存,即不再保存本地變量的內存。 – 4386427