POJ_2255

解题:

    比较直接,由二叉树pre-order和in-order求后序, 可以重构树再遍历,更好的方法是找到三种序列的关系,直接求解(先左后右, 不断的找到子树的根,然后压到结果栈,最后出栈次序就是后序遍历)。

注意:

    1. 从效率考虑,应该用栈迭代,而不要用递归。

    2. 最后遍历结果栈的时候,犯了很2的错误,debug好9,一定吸取教训。


//144k  0ms

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;

struct Tree {
  int p_st, p_end, in_st, in_end;
};

char pre[27], in[27];

int main() {
  while (scanf("%s %s", pre, in) != EOF) {
    stack<char> post;
    stack<Tree> tree_stack;
    Tree tree = {0, strlen(pre) - 1, 0, strlen(in) - 1};
    tree_stack.push(tree);
    while (tree_stack.size()) {
      tree = tree_stack.top();
      tree_stack.pop();
      if (tree.p_st <= tree.p_end && tree.in_st <= tree.in_end) {
        post.push(pre[tree.p_st]);
        for (int i = tree.in_st; i <= tree.in_end; ++i) {
          if (in[i] == pre[tree.p_st]) {
            Tree left = {tree.p_st + 1, tree.p_st + i - tree.in_st, 
              tree.in_st, i - 1};
            tree_stack.push(left);
            Tree right = {tree.p_st + i - tree.in_st + 1, tree.p_end,
              i + 1, tree.in_end}; 
            tree_stack.push(right);
            break;
          }
        }
      }
    }
    for ( ; post.size(); post.pop())
      printf("%c", post.top());
    printf("\n");
  }
  return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值