建立二叉树的二叉链表(严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;
}

 

 

 

在计算机科学中,将二叉树转换为二叉链表并行计算其遍历顺是一个常见的操作。首,我们需要了解如何构建二叉链表: 1. **节点结构**:每个节点包含两个指针,一个是值(Node.value),另一个是指向左孩子的指针(Node.left),另一个是指向右孩子的指针(Node.right)。如果某个孩子不存在,则对应指针为null。 2. **遍历**:对于二叉链表遍历,顺是根节点 -> 左子树 -> 右子树。可以按照这个顺创建节点,并链接它们。 - 创建根节点。 - 如果当前节点有左孩子,递归地将其左子链表转换为二叉链表。 - 将当前节点连接到根节点的左孩子位置。 - 如果当前节点有右孩子,继续对右子树进行同样的处理。 3. **中遍历**:根节点 -> 左子树 -> 右子树。对于已转换的链表,从根开始,访问左子树,然后访问根,最后访问右子树。 4. **后遍历**:左子树 -> 右子树 -> 根节点。遍历结束后,需要额外记录下左右孩子的链表,才能倒恢复原状。 为了输出这三种遍历结果,我们可以编写三个函数分别进行遍历,并打印出节点的值。例如,在Python中,你可以这样做: ```python def in_order_traversal(root): # 中遍历实现 ... def pre_order_traversal(root): # 遍历实现 ... def post_order_traversal(root): # 后遍历实现 ... # 转换二叉树二叉链表并调用上述遍历函数 root = convert_to_binary_link_list(your_tree) print("遍历:", pre_order_traversal(root)) print("中遍历:", in_order_traversal(root)) print("后遍历:", post_order_traversal(root)) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值