树的遍历主函数该怎么改

没语法错误,输出没结果


#include <stdio.h>
typedef int ElemType;
typedef struct LBinaryTreeNode
{
ElemType data; 
struct LBinaryTreeNode *lchild; 
struct LBinaryTreeNode *rchild; 
}LPBTreeNode;

LPBTreeNode *leftchild(LPBTreeNode *p){
if(p==NULL) return NULL;
return p->lchild;
}

LPBTreeNode *rightchild (LPBTreeNode *p){
if(p==NULL) return NULL;
return p->rchild;
}

LPBTreeNode *createbintree(void){
LPBTreeNode *pbnode;
char ch;
scanf("%c",&ch);
if(ch=='#') pbnode=NULL;
else
pbnode=(LPBTreeNode*) malloc(sizeof(LPBTreeNode));
if(pbnode==NULL)
printf("Out of space!\n");
return pbnode;
pbnode->data=ch;
pbnode->lchild=createbintree(); 
pbnode->rchild=createbintree(); 
return pbnode;
}

void preorder(LPBTreeNode *t)
{
if(t==NULL) return;
printf("%d",t->data) ;
preorder(t->lchild);
preorder(t->rchild);
}

void inorder(LPBTreeNode *t)
{
if(t==NULL) return;
inorder(t->lchild);
printf("%d",t->data) ;
inorder(t->rchild);
}

void postorder(LPBTreeNode *t){
if(t==NULL) return;
postorder(t->lchild);
postorder(t->rchild);
printf("%d",t->data) ;
}

int main()
{
LPBTreeNode *p;
p=createbintree();
printf("先序遍历结果: \n");
preorder(p);
printf("\\n中序遍历结果: \n");
inorder(p);
printf("\\n后序遍历结果: \n");

return 0;
}

第一步看到你使用了动态分配内存但是头包没了,这里面错误太多了,pbnode空指针的情况你也没考虑,下面是修改后的code:

#include <stdio.h>
#include <stdlib.h> 
typedef int ElemType;
typedef struct LBinaryTreeNode
{
    ElemType data;
    struct LBinaryTreeNode *lchild;
    struct LBinaryTreeNode *rchild;
} LPBTreeNode;

LPBTreeNode *leftchild(LPBTreeNode *p)
{
    if(p==NULL) return NULL;
    return p->lchild;
}

LPBTreeNode *rightchild (LPBTreeNode *p)
{
    if(p==NULL) return NULL;
    return p->rchild;
}

LPBTreeNode *createbintree(void)
{
    LPBTreeNode *pbnode;
    char ch;
    scanf("%c",&ch);
    if(ch=='#') pbnode=NULL;
    else
    {
        pbnode=(LPBTreeNode*) malloc(sizeof(LPBTreeNode)); 
        if(pbnode==NULL)
        {
            printf("Out of space!\\n");
            exit(1); 
        }
        pbnode->data=ch;
        pbnode->lchild=createbintree();
        pbnode->rchild=createbintree();
    }
    return pbnode; 
}

void preorder(LPBTreeNode *t)
{
    if(t==NULL) return;
    printf("%d",t->data) ;
    preorder(t->lchild);
    preorder(t->rchild);
}

void inorder(LPBTreeNode *t)
{
    if(t==NULL) return;
    inorder(t->lchild);
    printf("%d",t->data) ;
    inorder(t->rchild);
}

void postorder(LPBTreeNode *t)
{
    if(t==NULL) return;
    postorder(t->lchild);
    postorder(t->rchild);
    printf("%d",t->data) ;
}

int main()
{
    LPBTreeNode *p;
    p=createbintree();
    printf("先序遍历结果: \\n");
    preorder(p);
    printf("\\n中序遍历结果: \\n"); 
    inorder(p);
    printf("\\n后序遍历结果: \\n");
    postorder(p);
    return 0;
}