树的存储

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 100;//树的节点
const int maxm = 10000;//树的边。
int s[maxn];

struct node {
    int tail;
    int next;
}edge[maxm];

void dfs(int u) {//搜索一遍。
    for(int i = s[u]; i != -1; i = edge[i].next) {
        printf("%d -> %d\n", u, edge[i].tail);
        dfs(edge[i].tail);
    }
}

void output(int u) {//遍历
    for(int i = s[u]; i != -1; i = edge[i].next) {
        printf("%d - > %d\n", u, edge[i].tail);
    }
}

int main()
{
    int n;
    int from, to;//边的起点和重点。
    while(scanf("%d", &n)==1) {
        memset(s, -1, sizeof(s));
        for(int i = 0; i < n-1; i++) {
            scanf("%d%d", &from, &to);
            edge[i].tail = to;
            edge[i].next = s[from];
            s[from] = i;
        }
        int root = 1;//自己定义1为根节点。
        dfs(root);//从根节点开始搜索。
        for(int i = 1; i <= n; i++) {
            output(i);
        }
    }
    return 0;
}
/***
Test:
6
1 2
1 4
2 3
4 5
4 6
***/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值