测试数据:
8
1 2
1 7
1 4
2 8
2 5
4 3
3 9
4 6
注意点:
- h存放父节点,h的下标表示父节点的值,e表示子结点的值,ne表示兄弟节点的下一个位置
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010;
int n;
int h[N], e[N], ne[N], idx = 0;
queue<int> q;
void add (int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
void bfs(int root){
q.push(root);
while(q.size())
{
for(int i = h[q.front()]; i != -1; i = ne[i])
q.push(e[i]);
cout << q.front() << ' ';
q.pop();
}
return;
}
void dfs(int root){
cout << root << ' ';
for (int i = h[root]; i != -1; i = ne[i])
dfs(e[i]);
}
int main(){
cin >> n;
memset(h, -1, sizeof h);
for(int i = 0; i < n - 1; i ++)
{
int a, b;
cin >> a >> b;
add(a, b);
}
puts("brand first search:");
bfs(1);
puts("");
puts("depth first search:");
dfs(1);
return 0;
}
输出:
brand first search:
1 4 7 2 6 3 5 8 9
depth first search:
1 4 6 3 9 7 2 5 8
模板就这么个模板,剩下的就是不同情境下的应用变换了