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

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

    Description

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

    Input

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

    Output

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

    Sample

    Input 

    2
    abdegcf
    dbgeafc
    xnliu
    lnixu

    Output 

    dgebfca
    abcdefg
    linux
    xnuli
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    char a[1005],b[1005];
    struct node
    {
        int date;
        struct node *l,*r;
    };
    struct node *creat(int len,char a[51],char b[51])
    {int i;
        struct node *root;
        if(len==0)
        {
            return NULL;
    
        }
        root=(struct node*)malloc(sizeof(struct node));
        root->date=a[0];
        for(i=0;i<len;i++)
        {
            if(b[i]==a[0])
                break;
        }
        root->l=creat(i,a+1,b);
        root->r=creat(len-i-1,a+i+1,b+i+1);
        return root;
    };
    void cengxu(struct node * root)
    {
        struct node * temp[100];                                //关键中间变量存放每一层的数据
        int in = 0, out = 0;
        temp[in++] = root;                                      //每次把这一层存入,然后输出的时候就把他的左右节点存入
        while(in > out)                                         //例如一颗完全二叉树abcdefg  输出a的时候把bc放入,输出b的时候把b
        {                                                       //的孩子放入也就是de,再输出c并且放入孩子fg,依次这样,达到层序的要求
            if(temp[out])
            {
                printf("%c",temp[out]->date);
                temp[in++] = temp[out]->l;
                temp[in++] = temp[out]->r;
            }
            out++;
        }
    }
    void houxu(struct node *root)
    {
        if(root)
        {
            houxu(root->l);
            houxu(root->r);
            printf("%c",root->date);
        }
    }
    int main()
    {int n,len;
    scanf("%d",&n);
    struct node *root;
    while(n--)
    {
        scanf("%s",a);
        scanf("%s",b);
        len=strlen(a);
        root=creat(len,a,b);
        houxu(root);
        printf("
    ");
        cengxu(root);
        printf("
    ");
    }
        return 0;
    }
  • 相关阅读:
    将oh-my-zsh编程真正的my zsh
    Linux Shell 程序调试
    (64位)本体学习程序(ontoEnrich)系统配置说明文档
    Shell编程——vim常用命令
    Morris Traversal 方法遍历二叉树(非递归、不用栈,O(1)空间)
    206. Reverse Linked List
    欧几里德算法求解最大公约数
    25. Reverse Nodes in k-Group
    86. Partition List
    24. Swap Nodes in Pairs
  • 原文地址:https://www.cnblogs.com/xiaolitongxueyaoshangjin/p/12703286.html
Copyright © 2011-2022 走看看