P1229 遍历问题

考点

  • 二叉树

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <bits/stdc++.h>
using namespace std;
//前序序列和后序序列
string pre, post;

int main()
{
cin >> pre >> post;
int n = 0;
for (int i = 0, idx; i < pre.length() - 1; ++i)
for (int j = 1; j < post.length(); ++j)
{
if (pre[i] == post[j] && pre[i + 1] == post[j - 1])
++n;
}
cout << (1 << n);
return 0;
}

思路

通过作图可以发现,如果父结点只有一个孩子,在知道前序后序的情况下有不同的中序遍历

由于前序的输出规则是中左右,而后序的输出规则是左右中,显然:

  • 如果缺少左孩子,那么前序输出为中右,后序输出为右中
  • 如果缺少右孩子,那么前序输出为中左,后序输出为左中

找到满足这样的父结点数n后,根据乘法原理,每个这样的父结点都有两种可能性:有左孩子或者右孩子

所以最终结果应为2n