2016-11-04 54 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