程序在二进制搜索树中插入第二个节点时崩溃

时间:2016-11-04 04:42:22

标签: c pointers struct binary-tree

这里我编写了一个代码来实现二进制搜索tree.it在插入根节点时没有给出任何错误。但每当我尝试插入子节点时,我都会收到以下警告

  

传递推送不兼容指针类型的参数1

     

预期的struct node **但是参数是struct node *

     

传递推送不兼容指针类型的参数1

然后程序崩溃了。这段代码可能出错了吗?

#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 个答案:

答案 0 :(得分:2)

问题在于这种类型的行:

import json
ex = json.loads(request.form.get('ex'))
print ex

push((*root_node)->left,newNode); (*root_node)->left,但您的函数需要struct node*(双指针)。所以你需要改变:

struct node**

除此之外,你不能像在这里那样将局部变量放在树中:

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

使用void insert(int value){ struct node newNode ; // Local variable 代替

malloc

答案 1 :(得分: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);
}