POJ_2255
来源:互联网 发布:淘宝html模板 编辑:程序博客网 时间:2024/06/05 05:31
解题:
比较直接,由二叉树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;}
- POJ_2255
- POJ_2255
- poj_2255 Tree Recovery(已知前序遍歷和中序遍歷求後序遍歷)
- Oracle利用SQL*PLUS的spool功能抽取数据
- org.apache.tomcat.util.bcel.classfile.ClassFormatException: null is not a Java .class file
- C/C++中extern关键字详解
- char* 与LPTSTR (或LPCTSTR)及CString 之间的转换
- HTMLEncode
- POJ_2255
- 黑马程序员 IO流
- V4L2中命令在内核中来龙去脉
- bashrc and bash_profile 等!!!!
- DirectByteBuffer
- 第一道题目:一个美国人在菜市场上做生意。第一次,8美元买了一只鸡,9美元卖掉了;第二次,10美元买了同样的一只鸡,11美元又卖掉了。
- linux实现抓包 (使用原始套接字数据连路层协议)
- 查询和修改 Oracle 参数
- C语言的谜题