注册 登录
编程论坛 数据结构与算法

由先序序列、中序序列构建二叉树,大家看看这个程序问题出在什么地方了?

YAOYINGCHONG 发布于 2012-11-21 15:33, 340 次点击
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 100
typedef struct node
{
char data;
struct node *lchild,*rchild;
}BiNode;
void createBiTree(BiNode *root,char a[],int a_start,int a_end,char b[],int b_start,int b_end)
{
    int k;
    char ch;
    if(a_start>a_end)
        root=NULL;
    else
    {
        ch=a[a_start];
        k=b_start;
        while(b[k]!=ch)
            k++;
        root=(BiNode *)malloc(sizeof(BiNode));
        root->data=ch;
        createBiTree(root->lchild,a,a_start+1,a_start+k-b_start,b,b_start,k-1);
        createBiTree(root->rchild,a,a_start+k-b_start+1,a_end,b,k+1,b_end);
    }
}
void preorder(BiNode *root)
{
    if(root!=NULL)
    {printf("%c",root->data);
    preorder(root->lchild);
    preorder(root->rchild);
    }
}
void inorder(BiNode *root)
{
    if(root)
    {
        inorder(root->lchild);
            printf("%c",root->data);
            inorder(root->rchild);
    }
}
void main()
{
    char a[N],b[N];
    BiNode *root;
    printf("输入先序序列:");
    gets(a);
    printf("输入中序序列:");
    gets(b);
    createBiTree(root,a,0,strlen(a)-1,b,0,strlen(b)-1);
    printf("\n先序序列:");
    preorder(root);
    printf("\n中序序列:");
    inorder(root);
    printf("\n");
}


2 回复
#2
青春无限2012-11-21 22:28
看看
#3
一个孩子2012-11-22 22:35
我只会先序列创建二叉树~~
1