时间限制:1000MS 代码长度限制:10KB
提交次数:0 通过次数:0
题型: 编程题 语言: G++;GCC
Description二叉树的三种遍历都可以通过递归实现。 如果我们知道一棵二叉树的先序和中序序列,可以用递归的方法求后序遍历序列。
两行,第一行一个字符串,表示树的先序遍历,第二行一个字符串,表示树的中序遍历。 树的结点一律用小写字母表示,且字符串长度不超过30。
一个字符串,树的后序序列。
abcde bcade
cbeda
30002692
7
利用先序遍历和中序遍历的数据来确定整棵树的结构,然后根据这棵树的结构来进行一次后序遍历即可。
那么应该如何来进行这样的操作呢?首先先明确先序遍历和中序遍历的特点。
#include#include using namespace std; string preorder, inorder; char post[1000] = { 0 }; int p = 0; void makepost(int i, int start, int end) { if (start == end) { post[p++] = inorder[start]; return; } int j = start; while (preorder[i] != inorder[j]) j++; if (j != start) makepost(i + 1, start, j - 1); if (j != end) makepost(i + j - start + 1, j + 1, end); post[p++] = inorder[j]; } int main() { cin >> preorder >> inorder; int len = preorder.length(); makepost(0, 0, len - 1); for (int i = 0; i < len; i++) cout << post[i]; }



