Search code examples
cpointersbinary-treepointer-to-pointer

image of binary tree and pointer to pointer


I am making a simple program of how to make a binary tree which is the image of given binary tree ..

    #include <stdio.h>
    #include <stdlib.h>

    typedef struct tree { int data; struct tree * left ; struct tree * right} tree;

 int main()  
 {  
    tree * t = malloc(sizeof(tree));

    t->data = 12;
    t->left = malloc(sizeof(tree));
    t->right = malloc(sizeof(tree));

    t->left->data = 13;
    t->right->data = 16;

    t->left->left =NULL;
    t->left->right =NULL;

    t->right->left =NULL;
    t->right->right =NULL;

    inorder(t);

    tree * x = NULL   ;
    reverse(t, &x);

    inorder(x);
    }

// reverse is to create image of binary tree 
    void reverse (tree * t , tree ** r){

    if(t == NULL) return;

    *r = (tree *)malloc(sizeof(tree));

    (*r)->data = t->data;
    (*r)->left = NULL;
    (*r)->right = NULL;

    reverse(t->right,&((*r)->left) );
    reverse(t->left,&((*r)->right));

    }

    void inorder(tree *t)
    { if(t==NULL) return;

       printf("%d ", t->data);
       inorder( t->left);
       inorder( t->right);
    }

This is giving a Segmentation Fault .. Plz help ........


Solution

  • Replace

    reverse(t->right,((*r)->left) );
    reverse(t->left,((*r)->right));
    

    to

    reverse(t->right, &((*r)->left));
    reverse(t->left, &((*r)->right));
    

    and try again.