0

When passing "pointer to pointer" to a function getting segmentation fault.Code is generating Binary search tree through insert function. Insert function is getting pointer to root node and a key value which it inserts at correct position

#include<iostream>
#include<stdlib.h>
strong text
using namespace std;

struct node
{
    int data;
    struct node* left;
    struct node* right;

};

void insert(struct node** node,int data)    
{
    if( *node == 0 )
    {
        (*node) = (struct node* ) malloc(sizeof(struct node));
        (*node)->data = data;
        (*node)->left = 0;
        (*node)->right = 0; 
    }
    else if(data < ((*node) -> data)){      
        insert((&((*node) -> left)),data);
    }
    else if(data > ((*node)->data)){
        insert((&((*node)->right)),data);
    }
}

void inordertreversal(struct node* node)
{
    inordertreversal(node->left);
    cout << node->data;
    inordertreversal(node->right);
}

int main()
{
    struct node *root = 0;
    insert(&root,10);
    insert(&root,6);
    inordertreversal(root);

    return 0;
}

Help much appreciated

1 Answer 1

1

Check next nodes everytime:

void inordertreversal(struct node* node)
{
    if (node->left)
        inordertreversal(node->left);

    cout << node->data;

    if (node->right)
        inordertreversal(node->right);  
}

After this:

$ g++ example.c -o example && ./example
6
10
Sign up to request clarification or add additional context in comments.

2 Comments

And I would add ''if (node == 0) return;'' at the beginning
Thanks , din't analyse properly inorder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.