UVa-536 习题6-3 二叉树重建(Tree Recovery,ULM 1997)

来源:互联网 发布:班服制作软件 编辑:程序博客网 时间:2024/06/01 08:07

原题链接: UVA-536

题目大意:

 输入一棵二叉树的先序遍历和中序遍历序列,输出后序遍历序列。

解题思路:

 很基础的一道二叉树的题,和紫书中第六章中的一道例题很相似,边递归建树边输出。后序序列输出时应该将输出放在两个递归函数后面就可以后序序列。不难,不过还有些细节还是需要主要,比如传参的时候左右子树分别在先序和中序的位置需要注意。

代码:

#include<iostream>#include<string>#include<cstring>using namespace std;string preord, inord;void crt_tree(int L1, int R1, int L2, int R2,int n){if (L1 > R1 || L2 > R2)return;char root = preord[L1];int pos=0;while (inord[pos] != root) pos++;int len_left = pos - L2,len_right = R2 - pos;crt_tree(L1 + 1, L1 + len_left, L2, pos - 1, 2 * n);crt_tree(R1 - len_right+1, R1, pos + 1, R2, 2 * n + 1);cout << root;}int main(){while (cin >> preord>> inord){int len = preord.length();crt_tree(0, len - 1, 0, len - 1, 1);cout << endl;  }return 0;}


阅读全文
0 0