一、题目大意
给出二叉树的前序与中序遍历,输出其后续遍历
二、解题思路
使用递归建树,然后递归遍历。 每次递归建树过程执行以下图示:
当框中为空时停止递归过程
三、代码
#include<iostream>
using namespace std;
const int MAX = 27;
struct Node
{
Node* left;
Node* right;
char ch;
}Tree[MAX];
int cnt;
Node* creat(char ch)
{
Tree[cnt].ch = ch;
Tree[cnt].left = NULL;
Tree[cnt].right = NULL;
return &Tree[cnt++];
};
Node* build(string pre, string mid)
{
if(pre.length() == 0)
return NULL;
int p = mid.find(pre[0]);
string mid_left = mid.substr(0, p);
string mid_right = mid.substr(p+1, 1000);
string pre_left = pre.substr(1, p);
string pre_right = pre.substr(p+1, 1000);
struct Node *temp = creat(pre[0]);
temp->left = build(pre_left, mid_left);
temp->right = build(pre_right, mid_right);
return temp;
};
void print_last(Node*T)
{
if(T == NULL)
return;
print_last(T->left);
print_last(T->right);
cout << T->ch;
}
int main()
{
string pre, mid;
while(cin >> pre >> mid)
{
cnt = 0;
struct Node *T = build(pre, mid);
print_last(T);
cout << endl;
}
return 0;
}