Pat知识储备——使用邻接表表示的树,使用bfs和dfs

测试数据:
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

模板就这么个模板,剩下的就是不同情境下的应用变换了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值