15 数据结构课程设计小组任务15:树的孩子兄弟链表

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <sstream>
#include <stack>
#include <map>
#include <ctime>
#include <array>
#include <set>
#include <list>
using namespace std;
struct ArcNode
{
    int adj;
    ArcNode *nextarc;
};
struct vNode
{
    string data;
    ArcNode *firstarc;
};
struct Node
{
    struct vNode arr[100];
    int length;
};
struct node
{
    string data;
    int parent;
};
void create(struct Node &T, vector<node> v, int len)
{
    T.length = len;
    for (int i = 0; i < len; i++)
    {
        T.arr[i].data = v[i].data;
        T.arr[i].firstarc = NULL;
    }
    for (int i = len - 1; i >= 0; i--)
    {
        ArcNode *p = new ArcNode;
        p->adj = i;
        p->nextarc = T.arr[v[i].parent].firstarc;
        T.arr[v[i].parent].firstarc = p;
    }
}
int find_num(struct Node T, int u, int v)
{
    if (u < 0 || u > T.length)
        return -1;
    ArcNode *p;
    p = T.arr[u].firstarc;
    while (p != NULL)
    {
        if (p->adj == v)
        {
            if (p->nextarc == NULL)
                return -1;
            else
                return p->nextarc->adj;
        }
        p = p->nextarc;
    }
    return -1;
}
int visit[100] = {0};
void preDFS(struct Node T, int v)
{
    if (v == 0)
        cout << T.arr[v].data;
    else
        cout << ',' << T.arr[v].data;
    visit[v] = 1;
    if (T.arr[v].firstarc == NULL)
        return;
    for (int w = T.arr[v].firstarc->adj; w >= 0; w = find_num(T, v, w))
    {
        if (!visit[w])
            preDFS(T, w);
    }
}
int visited[100] = {0};
void postDFS(struct Node T, int v)
{
    visit[v] = 1;
    if (T.arr[v].firstarc == NULL)
        return;
    for (int w = T.arr[v].firstarc->adj; w >= 0; w = find_num(T, v, w))
    {
        if (!visited[w])
            postDFS(T, w);
        cout << T.arr[w].data << ',';
    }
}
int leaf(struct Node T)
{
    int sum = 0;
    for (int i = 0; i < T.length; i++)
    {
        if (T.arr[i].firstarc == NULL)
            sum++;
    }
    return sum;
}
int main()
{
    vector<node> v;
    struct node t;
    char ch;
    string s;
    int len = 0;
    while (cin >> t.data)
    {
        cin.get(ch);
        t.parent = 0;
        len++;
        v.push_back(t);
        if (ch == '\n')
            break;
    }
    for (int i = 0; i < len; i++)
    {
        int num;
        cin >> num;
        v[i].parent = num;
    }
    struct Node T;
    create(T, v, len);
    preDFS(T, 0);
    cout << endl;
    postDFS(T, 0);
    cout << T.arr[0].data << endl;
    int sum;
    sum = leaf(T);
    cout << sum << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值