建立二叉树的二叉链表(严6.65)根据先序序列和中序序列输出后序序列

 

Description

已知一棵二叉树的前序序列和中序序列分别存于两个一维数组中,试编写算法建立该二叉树的二叉链表

 

 

Input

分两行分别输入一棵二叉树的前序序列和中序序列。

 

 

Output

输出该二叉树的后序序列。

 

 

SampleInput        ABDFGCEH

                               BFDGACEH

 

 

 

SampleOutput      FGDBHECA

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
typedef struct node
{
    char data;
    struct node*lchild;
    struct node*rchild;
}BiTNode,*BiTree;
void midprecreat(BiTree*root,char mid[],char pre[],int lm,int rm,int lp,int rp)
{
    *root=(BiTree)malloc(sizeof(BiTNode));
    (*root)->data=pre[lp];
    (*root)->lchild=NULL;
    (*root)->rchild=NULL;
   int pos=lm;
   while(mid[pos]!=pre[lp])
        pos++;
    int childlen=pos-lm;//用来控制子树在字符串中的范围
    if(pos>lm)//有左子树,递归创建
        midprecreat((&((*root)->lchild)),mid,pre,lm,pos-1,lp+1,lp+childlen);
    if(pos<rm)//有右子树,递创建
        midprecreat((&((*root)->rchild)),mid,pre,pos+1,rm,lp+childlen+1,rp);
}
void print(BiTree p)
{      if(p != NULL)
       {
              print(p->lchild);  //遍历左子树
              print(p->rchild); //遍历右子树
              printf("%c",p->data);     //输出该结点
       }
}
int main()
{
    char    pre[100];            //存储先序序列
    char    mid[100];            //存储中序序列
    int n;
    BiTree root;
    gets(pre);
    n=strlen(pre);
    gets(mid);
    midprecreat(&root,mid,pre,0,n-1,0,n-1);
    print(root);
    return 0;
}

 

 

 

下面是C语言实现: ```c #include <stdio.h> #include <stdlib.h> typedef struct TreeNode { char data; struct TreeNode *left; struct TreeNode *right; } TreeNode; TreeNode *createTree(char *preorder, char *inorder, int len) { if (len == 0) { return NULL; } TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode)); root->data = *preorder; int i; for (i = 0; i < len; i++) { if (*(inorder + i) == *preorder) { break; } } root->left = createTree(preorder + 1, inorder, i); root->right = createTree(preorder + i + 1, inorder + i + 1, len - i - 1); return root; } void preorder(TreeNode *root) { if (root != NULL) { printf("%c ", root->data); preorder(root->left); preorder(root->right); } } void inorder(TreeNode *root) { if (root != NULL) { inorder(root->left); printf("%c ", root->data); inorder(root->right); } } void postorder(TreeNode *root) { if (root != NULL) { postorder(root->left); postorder(root->right); printf("%c ", root->data); } } int main() { char preorder[] = "ABDECF"; char inorder[] = "DBEAFC"; TreeNode *root = createTree(preorder, inorder, 6); printf("先序遍历:"); preorder(root); printf("\n中序遍历:"); inorder(root); printf("\n后序遍历:"); postorder(root); printf("\n"); return 0; } ``` 输出结果为: ``` 先序遍历:A B D E C F 中序遍历:D B E A F C 后序遍历:D E B F C A ``` 该程序的核心是 `createTree` 函数,它通过递归调用实现了先序遍历序列建立二叉树的功能。程序中还实现了先序遍历、中序遍历、后序遍历的函数,用于输出二叉树的遍历结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值