zoukankan      html  css  js  c++  java
  • XYNUOJ 2390【二叉树遍历2】

    题目描述

    二叉树的前序、中序、后序遍历的定义:
    前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
    中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
    后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
    给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。

    输入

    两个字符串,其长度n均小于等于26。
    第一行为前序遍历,第二行为中序遍历。
    二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。

    输出

    输入样例可能有多组,对于每组测试样例,
    输出一行,为后序遍历的字符串。

    样例输入

    ABC
    CBA
    ABCDEFG
    DCBAEFG
    

    样例输出

    CBA
    DCBGFEA

    题解:先在先序遍历中找到二叉树的根节点(也就是先序遍历的第一个值),然后再去中序遍历中找到根节点,那么就知道中序遍历中,根节点的左边为左子树,右边为右子树,然后找出左子树的后序遍历和右子树的后序遍历,最后再拼接在一起。

    代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    #include <vector>
    #include <set>
    #include <map>
    using namespace std;
    void toPost(char in[],char pre[],int len,char post[]){
        int i;
        if(len<=0) return ;
        for(i=0;i<len;i++){
            if(in[i]==pre[0])
                break;
        }
        post[len-1]=pre[0];
        toPost(in,pre+1,i,post);
        toPost(in+i+1,pre+i+1,len-i-1,post+i);
    }
    int main()
    {
        char in[27],pre[27],post[27];
        int len;
        while(~scanf("%s",pre)){
            scanf("%s",in);
            len=strlen(in);
            toPost(in,pre,len,post);
            for(int i=0;i<len;i++){
                printf("%c",post[i]);
            }
            printf("
    ");
        }
        return 0;
    }
    

  • 相关阅读:
    Swift中的参数内部名称和外部名称
    iOS 发布流程
    解决xcode iOS真机调试正常,模拟器失败问题
    iOS 解决ipv6问题
    cocos2dx 字体描边遇到的描边缺失的bug
    cocos2dx for iOS fmod的音效引擎接入
    skynet 学习笔记-sproto模块(2)
    cocos2dx for android 接入 fmod的过程
    skynet 学习笔记-netpack模块(1)
    linux 安装并且设置环境lua环境变量
  • 原文地址:https://www.cnblogs.com/kzbin/p/9205195.html
Copyright © 2011-2022 走看看