注册 登录
编程论坛 C++教室

新人学习不知道为什么在主函数中没有调用输入的语句,好像直接跳过了,那位帮忙检查下,大概是在插入的时候出错了

lizexu 发布于 2018-05-20 17:50, 1709 次点击
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max 100
typedef struct BiTNode
{
    char date;
    struct BiTNode *lchild;
    struct BiTNode *rchild;
}BiTNode,*BiTree;
int layer(BiTree b,int *a);
int crtTNode(BiTree *t);
int treeprint(BiTree t,int level);
int insert(BiTree *t,char x);                                                                                                                                                                                                                                          
int main()
{
    BiTree bt;int m=0,n=0;
    printf("输入需要进入二叉树的字符串#表示为空:\n");
    crtTNode(&bt);
    treeprint(bt,n);
    printf("输入需要插入的字母:\n");
    char z;
    scanf("%c",&z);
    insert(&bt,z);
    treeprint(bt,n);
    layer(bt,&m);
}
int crtTNode(BiTree *t)
{
    char ch;
    scanf("%c",&ch);
    if(ch=='#') *t=NULL;
    else
    {
        *t=(BiTree)malloc(sizeof(BiTNode));
        (*t)->date=ch;
        crtTNode(&(*t)->lchild);
        crtTNode(&(*t)->rchild);
    }
    return 1;
}
int layer(BiTree b,int *a)
{
    if(b)
    {
        layer(b->lchild,&(*a));
        printf("%c",b->date);
        *a=*a+1;
        layer(b->rchild,&(*a));
    }
    return 1;
}
int treeprint(BiTree t,int level)
{
    if(!t)return 0;
    treeprint(t->rchild,level+1);
    for(int i=0;i<level;i++)
    printf(" ");
    printf("%c\n",t->date);
    treeprint(t->lchild,level+1);
    return 1;
}
int insert(BiTree *t,char x)
{
    if(*t==NULL)
    {
        *t=(BiTree)malloc(sizeof(BiTNode));
        if(*t==NULL) printf("can't malloc ,insert operation failed");
        (*t)->date=x;
        (*t)->lchild=(*t)->rchild=NULL;
        return 1;
    }
    if(x>(*t)->date)
    {
        insert(&(*t)->rchild,x);
        return 1;
    }
    if(x<(*t)->date)
    {
        insert(&(*t)->lchild,x);
        return 1;
    }
}
1 回复
#2
lizexu2018-05-20 17:53
原本是想根据父母的节点加左右孩子的,确定插入的位置。但是改了好多遍都有问题,只能用比较大小的递归做,希望帮帮忙
1