已知二叉树的先序(前序)遍历及中序遍历,还原该二叉树并输出其后续遍历

已知二叉树的先序(前序)遍历及中序遍历,还原该二叉树并输出其后续遍历

#include 
   
   
    
    
#include 
    
    
     
     

typedef char datatype;
typedef struct node
{
    datatype data;
    struct node *lchild,*rchild;
} bintnode,*bintree;

//后序遍历输出当前二叉树
void postorder(bintree root)
{
    if(root==NULL)return;
    else
    {
        postorder(root->lchild);
        postorder(root->rchild);
        printf("%c",root->data);
    }
}
bintree buildBintree(char *pre,char *mid,int length)
{
    int divlen=0;//左子树的长度
    char *temp;
    if(length<=0)return NULL;
    bintree root=(bintree)malloc(sizeof(bintnode));
    root->data=*pre;
    temp=mid;//定义一个临时变量来存放中序遍历的序列
    while(*temp!=*pre&&temp!=NULL)//当找到时以该点为分割点,前面记录下长度为当前节点下的左子树
    {
    	divlen++;
        temp++;
    };
    root->lchild=buildBintree(pre+1,mid,divlen);//递归得出左子树
    root->rchild=buildBintree(pre+divlen+1,temp+1,length-divlen-1);//得出右子树
    return root;
}

int main()
{
    bintree root;
    char pre[100],mid[100];
    puts("请输入前序序列:");
    gets(pre);
    puts("请输入后续序列:");
    gets(mid);
    root=buildBintree(pre,mid,strlen(pre));
    puts("后续序列是:");
    postorder(root);
    return 0;
}

    
    
   
   

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值