原题:http://www.patest.cn/contests/mooc-ds2015spring/03-%E6%A0%912(Tree Traversals Again)
思路:push结点的顺序就是前序遍历的顺序,pop的顺序就是中序遍历的顺序,跟据前序与中序可还原二叉树
代码:
#include <cstdio>
#include <iostream>
#include <stack>
using namespace std;
typedef struct node{
int data;
struct node *left;
struct node *right;
}*BinTree;
BinTree pre_in(int *pre, int *in, int n)
{
if (n == 0)
return NULL;
BinTree T = (BinTree)malloc(sizeof(struct node));
T->data = *pre;
int *p = in;
for (; p < in + n; ++p){
if (*p == *pre) break;
}
int k = p - in;
T->left = pre_in(pre + 1, in, k);
T->right = pre_in(pre + k + 1, in + k + 1, n - k - 1);
return T;
}
bool first = true; //放到函数外作为全局变量 不然每次递归调用first都是新的各层函数内局部变量 都是true
void PostOrder(BinTree T)
{
if (T){
PostOrder(T->left);
PostOrder(T->right);
if (first){
printf("%d", T->data);
first = false;
}
else printf(" %d", T->data);
}
}
int main()
{
int n,t; //t存放push后面的数
char a[5]; //存放push或pop
int pre[30],in[30];
int i,j; //作为pre和in的索引
i = j = 0;
stack<int> s;
cin >> n;
while (j < n){
scanf("%s", a);
if (a[1] == 'u') {
scanf("%d", &t);
s.push(t);
pre[i++] = t;
}
else {
in[j++] = s.top();
s.pop();
}
}
BinTree T = pre_in(pre, in, n);
PostOrder(T);
return 0;
}