二进制树和指针指针的图像

时间:2014-03-31 07:27:56

标签: c pointers binary-tree pointer-to-pointer

我正在制作一个简单的程序,如何制作一个二叉树,这是给定二叉树的图像 ..

    #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);
    }

这会产生细分错误 .. Plz帮助........

3 个答案:

答案 0 :(得分:1)

正确的程序:

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

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

void reverse (tree * t , tree ** r);
void inorder(tree *t);

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

    t->data = 12;
    t->left = (tree *)malloc(sizeof(tree));
    t->right = (tree *)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)printf("%d ", t->data);
    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);
    }

答案 1 :(得分:1)

替换

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

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

再试一次。

答案 2 :(得分:0)

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

应该是

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

现在,tree*被投放为tree**。您可能在编译期间收到警告。