zoukankan      html  css  js  c++  java
  • [二叉树建树] 复原二叉树(前序遍历和中序遍历构建二叉树)

    题目描述

    小明在做数据结构的作业,其中一题是给你一棵二叉树的前序遍历和中序遍历结果,要求你写出这棵二叉树的后序遍历结果。

    输入

    输入包含多组测试数据。每组输入包含两个字符串,分别表示二叉树的前序遍历和中序遍历结果。每个字符串由不重复的大写字母组成。

    输出

    对于每组输入,输出对应的二叉树的后续遍历结果。

    样例输入

    DBACEGF ABCDEFG BCAD CBAD

    样例输出

    ACBFGED CDAB
     
    TODO:you need to add your analysis in here.
     
    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    using namespace std;
    
    struct node
    {
        char data;
        int layer;
        node * lchild,*rchild;
    };
    
    string prestr,instr;
    
    node * creat(int preL,int preR,int inL,int inR)
    {
        if(preL>preR) return NULL;
        node * root = new node;
        root->data=prestr[preL];
        int k;
        //在中序输出中找到preL的字符
        for(k=inL;k<=inR;k++)
        {
            if(instr[k]==prestr[preL]) break;
        }
        int numLeft=k-inL;
        root->lchild=creat(preL+1,preL+numLeft,inL,k-1);
        root->rchild=creat(preL+numLeft+1,preR,k+1,inR);
        return root;
    }
    
    void postOrder(node * root)
    {
        if(root==NULL)
        {
            return ;
        }
        postOrder(root->lchild);
        postOrder(root->rchild);
        cout<<root->data;
    }
    
    
    
    int main() 
    {
        while(cin>>prestr>>instr)
        {
            node * root;
            root=creat(0,prestr.length()-1,0,instr.length()-1);
            postOrder(root);
            cout<<endl;
        }
        return 0;
    }
     
     
     
  • 相关阅读:
    删除docker thin 空间解决文件满不能拉起docker问题
    kafka服务端和客户端均无法消费
    prometheus 配置支持consul动态拉取
    spring cloud consul配置
    使用arthas分析慢查询
    nginx日志格式配置
    spring secrity添加和去掉x-frame-options deny安全头
    java POI解析word为文本内容
    sublime text 3 插入当前时间
    CUnit 安装笔记
  • 原文地址:https://www.cnblogs.com/xiongmao-cpp/p/6430085.html
Copyright © 2011-2022 走看看