题意就是给你二叉树的bfs和dfs遍历,都是结点小的优先遍历
本来自己没做出来,不想写的,做了半天测试数据是对的,但是WA。因为看了一个大佬的解法,让我感慨万分,简洁而直接的解法,正确而清晰的思路,让我佩服的五体投地。充分运用的bfs,dfs,以及栈的性质,这句话很重要,代码真是艺术,总存在最简解法。
#include<iostream>
#include <string>
#include <string.h>
#include<vector>
#include<stack>
using namespace std;
const int maxn = 1000 + 5;
int bfs[maxn];
vector<int>tree[maxn];
int main()
{
int n; int temp;
while (cin >> n && n) {
for (int i = 1; i <= n; i++) {
cin >> temp; bfs[temp] = i; tree[i].clear();
}
int next;
cin >> next;
stack<int>sp;
sp.push(next);
for (int i = 1; i < n; i++) {
cin >> next;
while (1) {
int root = sp.top();
if (bfs[next] > bfs[root] + 1 || (bfs[root] + 1 == bfs[next] && root > next) || root == next) {//第二个判断就是结点小的优先搜索
tree[root].push_back(next);
sp.push(next); //加入要搜索子节点的栈
break;
}
else {
sp.pop();//没有搜索到子节点 回退上一个节点
}
}
}
for (int i = 1; i <= n; i++) {
cout << i << ":";
for (int j = 0,sz= tree[i].size(); j < sz; j++) {
cout << " "<<tree[i][j];
}
cout << endl;
}
}
//system("pause");
return 0;
}