UVA536 - Tree Recovery(递归)

来源:互联网 发布:unity3d模型文件格式 编辑:程序博客网 时间:2024/06/05 08:23

题目:UVA536 - Tree Recovery(递归)


题目大意:给出一棵二叉树的前序遍历和中序遍历,求后序遍历。


解题思路:根据前序遍历将中序遍历的序列分成一棵棵子树,知道这个子树只有一个节点,然后就可以将它按顺序放到后序数组值中了。


代码:

#include <cstdio>#include <cstring>const int N = 30;char preord[N], inord[N];char postord[N];int p1, p2, len;int search (char val) {for (int i = 0; i < len; i++)if (inord[i] == val)return i;}void build(int l, int r) {if (r - l < 1)return;int pos = search (preord[p1++]);build(l, pos);build(pos + 1, r);postord[p2++] = inord[pos];}int main () {while (scanf ("%s%s", preord, inord) != EOF) {p1 = p2 = 0;len = strlen (preord);build(0, len);postord[len] = '\0';printf ("%s\n", postord);}return 0;}


0 0
原创粉丝点击