Description
输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
Input
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。
Output
输出该二叉树的后序遍历序列。
Sample
Input
ABDCEF
BDAECF
Output
DBEFCA
C++
/*
time : 2021年6月23日19:12:58
result : accept
author : kirie
tips : r16:return NULL;(not root or void)
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define rep(i,a,n) for(int i=a;i<n;i++)
using namespace std;
const int N=1e4+7;
typedef struct TreeNode{
char val;
struct TreeNode* LChild;
struct TreeNode* RChild;
}Node;
Node* CreateTree(char pre[], char mid[], int len){
if(len <= 0)
return NULL;
Node *root = new Node;
root->val = pre[0];
int i;
for(i = 0;i < len; i++){
if(mid[i] == pre[0])
break;
}
root->LChild = CreateTree(pre+1, mid, i);
root->RChild = CreateTree(pre+1+i, mid+1+i, len-i-1);
return root;
}
void after_show(Node* root){
if(root){
after_show(root->LChild);
after_show(root->RChild);
cout<<root->val;
}
}
int main()
{
char str1[N],str2[N];
cin>>str1>>str2;
Node* root = new Node;
root = CreateTree(str1, str2, strlen(str1));
after_show(root);
cout<<endl;
return 0;
}
/*
ABDCEF
BDAECF
*/
principle