zoukankan      html  css  js  c++  java
  • SDUT2137 数据结构实验之求二叉树后序遍历和层次遍历

    数据结构实验之求二叉树后序遍历和层次遍历

    Time Limit: 1000MS Memory limit: 65536K

    题目描述

     已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。

    输入

     输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。

    输出

    每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列

    示例输入

    2
    abdegcf
    dbgeafc
    xnliu
    lnixu

    示例输出

    dgebfca
    abcdefg
    linux
    xnuli
    【code】
     1 #include<stdio.h>
    2 #include<stdlib.h>
    3 #include<string.h>
    4 typedef struct tree
    5 {
    6 char data;
    7 struct tree *l,*r;
    8 }tree;
    9 tree *creat(char *pre,char *in,int len)
    10 {
    11 int k;
    12 if(len<=0)
    13 return NULL;
    14 tree*head;
    15 head=(tree*)malloc(sizeof(tree));
    16 head->data=*pre;
    17 char *p;
    18 for(p=in;p!=NULL;p++)
    19 if(*p==*pre)
    20 break;// 在中序遍历的序列中得到与先序相同的节点
    21 k=p-in;
    22 head->l=creat(pre+1,in,k);//递归得到左子树
    23 head->r=creat(pre+k+1,p+1,len-k-1);//得到右子树
    24 return head;
    25 }
    26 void postorder(tree*t)
    27 {
    28 if(t)
    29 {
    30 postorder(t->l);
    31 postorder(t->r);
    32 printf("%c",t->data);
    33 }
    34 }
    35 void lorder(tree*t)
    36 {
    37 int front=0,rear=1;
    38 tree*q[100];
    39 q[0]=t;
    40 while(front<rear)
    41 {
    42 if(q[front])
    43 {
    44 printf("%c",q[front]->data);
    45 q[rear++]=q[front]->l;
    46 q[rear++]=q[front]->r;
    47 front++;
    48 }
    49 else
    50 front++;
    51 }
    52 }
    53 int main()
    54 {
    55 int t,len;
    56 char pre[51],in[51];//存储先序和中序遍历的序列
    57 tree*h;
    58 h=(tree*)malloc(sizeof(tree));
    59 scanf("%d%*c",&t);
    60 while(t--)
    61 {
    62 scanf("%s%s",pre,in);
    63 len=strlen(pre);
    64 h=creat(pre,in,len);
    65 postorder(h);
    66 printf("\n");
    67 lorder(h);
    68 printf("\n");
    69 }
    70 return 0;
    71 }
    
    

    1、从先序遍历中读入根节点
    2、从中序遍历中找到与根节点相等的元素,将中序序列分成两个部分,左边的为二叉树的
      
    左子树,右边为二叉树的右子树;
    3
    、递归调用得到根节点的左右子树

           层次遍历是看的别人的代码。。。

     

    myblog:http://www.bearac.com

     

     

  • 相关阅读:
    NYOJ 10 skiing DFS+DP
    51nod 1270 数组的最大代价
    HDU 4635 Strongly connected
    HDU 4612 Warm up
    POJ 3177 Redundant Paths
    HDU 1629 迷宫城堡
    uva 796
    uva 315
    POJ 3180 The Cow Prom
    POJ 1236 Network of Schools
  • 原文地址:https://www.cnblogs.com/pony1993/p/2371900.html
Copyright © 2011-2022 走看看