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

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

    Time Limit: 1000MS Memory limit: 65536K

    题目描述

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

    输入

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

    输出

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

    示例输入

    2
    abdegcf
    dbgeafc
    xnliu
    lnixu

    示例输出

    dgebfca
    abcdefg
    linux
    xnuli
    
    
    
    
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    typedef struct node
    {
    char data;
    struct node *l,*r;
    }tree;
    tree *creat(char *pre,char *in,int len)/*中序遍历中根节点的左边全都是左子树的中序,右边全是右子树中序。然而每个子树的先序序列的第一个节点是子树的根,而且向后移动中序查找得到的左子树节点数便可分开得到左右子树。因此可以用递归分而治之*/
    {
    tree *head;//创立根节点
    if(len<=0)
    return NULL;//当节点为零时表明数据完全潜入书中
    head = (tree *)malloc(sizeof(tree));
    char *p;

    head->data = *pre;//先序的第一个节点指定是当前子树的根
    for(p = in;p!=NULL;p++)
    if(*p == *pre) break;
    int lon = p-in;//左子树节点的个数
    head->l = creat(pre+1,in,lon);//分而治之创建左子树
    head->r = creat(pre+lon+1,p+1,len-lon-1);//分而治之创建右子树
    return head;
    }
    void cengci(tree *root)
    {
    tree *p[51];//用指针来控制。
    p[0] = root;
    int f = 0,r = 1;
    while(f < r)//每一个p[f]都是子树树根
    {
    if(p[f])//因为为二叉树所以最多有2个子树,且只有当二叉树不为空时才可能有数据,为空时即可跳过,不打印
    {
    printf("%c",p[f]->data);
    p[r++] = p[f]->l;
    p[r++] = p[f]->r;//
    }
    f++;
    }
    }

    last(tree * root)
    {
    if(root)
    {

    last(root->l);
    last(root->r);
    printf("%c",root->data);
    }
    }
    int main()
    {
    int n,i;
    char s0[1000],s1[1000];
    scanf("%d%*c",&n);
    while(n--)
    {
    gets(s0);
    gets(s1);

    char *in,*pre;

    pre = s0,in = s1;
    int len = strlen(s0);//节点数
    tree * root = creat(pre,in,len);//从两个字符串中找出树
    last(root);//后序遍历
    puts("");
    cengci(root);//层次遍历
    puts("");

    }
    return 0;
    }
  • 相关阅读:
    poj3669 广搜
    检索所有课程都选修的的学生的学号与姓名
    UVA10160 Servicing Stations
    uva11205 The broken pedometer 子集生成
    poj1101 the game 广搜
    poj3009 Curling 2.0 深搜
    poj 1564 Sum It Up 搜索
    HDU 2268 How To Use The Car (数学题)
    codeforces 467C George and Job(简单dp,看了题解抄一遍)
    HDU 2267 How Many People Can Survive(广搜,简单)
  • 原文地址:https://www.cnblogs.com/0803yijia/p/2381198.html
Copyright © 2011-2022 走看看