https://www.patest.cn/contests/pat-a-practise/1020 题目链接
解题思路如下:(两种思路)
1.题目输入后序和中序遍历树
2.1 直接通过后序和中序遍历树,建立该树(树数据结构可以采用结构体链表方式,或者用数组,也可以采用数组-链表方式,c++中比较简单用vector可以直接实现,推荐用第三种),然后在对树进行BFS遍历输出解即可
2.2 略过建立该树过程,直接对树进行BFS遍历输出结果,具体通过p类型的结构体queue数据结构来实现
两种算法的复杂度都为O(N)
坑点:无坑点,关键在于掌握树的遍历方式和熟练编程实现即可。
下列代码实现采用2.2的思路来实现,代码如下:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct p{
int left;
int right;
int left_i;
int right_i;
int root;
p(): left(0), right(0), left_i(0), right_i(0), root(0) {}
};
vector<int> p_o;
vector<int> i_o;
queue<p> ans;
vector<int> output;
int find_m(int left, int right, int left_i, int right_i, int root)
{
for(int i = left_i; i <= right_i; i++)
{
if(root == i_o[i])
{
return i - left_i;
}
}
return -1;
}
void generate_tree(int n)
{
int key;
p temp;
temp.left = 0;
temp.right = n;
temp.left_i = 0;
temp.right_i = n;
temp.root = p_o[n];
ans.push(temp);
while(!ans.empty())
{
p root, root_l, root_r;
root = ans.front();
ans.pop();
if(root.right > root.left)
{
key = find_m(root.left, root.right, root.left_i, root.right_i, root.root);
//cout << " " << root.root;
output.push_back(root.root);
root_l.left = root.left;
root_l.right = root.left + key -1;
root_l.left_i = root.left_i;
root_l.right_i = root.left_i + key - 1;
root_l.root = p_o[root.left + key - 1]; /*eccess the bodary*/
ans.push(root_l);
root_r.left = root.left + key;
root_r.right = root.right - 1;
root_r.left_i = root.left_i + key + 1;
root_r.right_i = root.right_i;
root_r.root = p_o[root.right - 1];
ans.push(root_r);
}
if(root.right == root.left)
{
//cout << " " << p_o[root.right];
output.push_back(p_o[root.right]);
}
}
}
int main(void)
{
string line;
while(getline(cin, line))
{
int n;
p_o.clear();
i_o.clear();
output.clear();
sscanf(line.c_str(), "%d", &n);
getline(cin, line);
stringstream ss(line);
for(int i = 0; i < n; i++)
{
int temp;
ss >> temp;
p_o.push_back(temp);
}
getline(cin, line);
stringstream sss(line);
for(int i = 0; i < n; i++)
{
int temp;
sss >> temp;
i_o.push_back(temp);
}
generate_tree(n-1);
cout << output[0];
for(unsigned int i = 1; i < output.size(); i++)
{
cout << " " << output[i];
}
cout << endl;
}
return 0;
}