描述
输入一棵二叉树的先序和中序遍历序列,输出其后序遍历序列。
格式
输入格式:
共两行,第一行一个字符串,表示树的先序遍历,第二行一个字符串,表示树的中序遍历。
输出格式:
一行,表示树的后序遍历序列。
样例
输入样例:
abdec
dbeac
输出样例:
debca
代码:
#include<iostream>
#include<string.h>
using namespace std;
struct TNode{
char data;
TNode *left;
TNode *right;
TNode(char c): data(c),left(NULL),right(NULL){}
};
TNode *build(string pre,string mid)//由先序和中序递归建立二叉树
{
if(pre.size()==0)
return NULL;
char c=pre[0];
TNode *root=new TNode(c);
int position=mid.find(c);//找到先序第一个元素在中序的位置
root->left=build(pre.substr(1,position) , mid.substr(0,position));
root->right=build(pre.substr(position+1), mid.substr(position+1));
return root;
}
int last(TNode *root)
{
if(root==NULL)
return 0;
last(root->left);
last(root->right);
cout<<root->data;
}
int main()
{
string pre,mid;
cin>>pre>>mid;
TNode *root;
root=build(pre,mid);
last(root);
return 0;
}