[二叉树建树] 复原二叉树(前序遍历和中序遍历构建二叉树)
题目描述
小明在做数据结构的作业,其中一题是给你一棵二叉树的前序遍历和中序遍历结果,要求你写出这棵二叉树的后序遍历结果。
输入
输入包含多组测试数据。每组输入包含两个字符串,分别表示二叉树的前序遍历和中序遍历结果。每个字符串由不重复的大写字母组成。
输出
对于每组输入,输出对应的二叉树的后续遍历结果。
样例输入
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; }
——来自 熊猫 [http://www.cnblogs.com/xiongmao-cpp/]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步