我需要使用图形方法创建一个二叉树,并且需要扫描文件中的节点数,每个节点索引和子级数。我使用了这段代码,但它总是给我一个异常,我该怎么办? ps。(图形应为指向节点的指针数组)
#include<iostream>
#include<fstream>
using namespace std;
#define MAX_CHILD 2
struct NODE {
int child[MAX_CHILD];
int count_child;
};
void construct_graph(NODE* G[],int num)
{
int n, index;
ifstream fp("data.txt", ios::in);
fp >> n;
for (int i = 0; i < n; i++)
{
fp >> index;
fp>>G[index]->count_child;
for (int j = 0; j < G[index]->count_child; j++)
{
fp>>G[index]->child[j];
}
}
}
void df_visited(NODE *G[], bool visited[], int v, int*nw)
{
if (visited[v])
return;
nw[v] = G[v]->count_child + 1;
cout << nw[v];
visited[v] = true;
for (int i = 0; i < G[v]->count_child; i++)
{
df_visited(G, visited, G[v]->child[i], nw);
}
}
void depth_first_print(NODE *G[], int size,int *nw)
{
int i;
bool *visited;
visited = new bool[size];
for (i = 0; i < size; i++)
visited[i] = false;
for (i = 0; i < size; i++)
{
if (!visited[i])
df_visited(G, visited, i,nw);
}
}
int main()
{
NODE **G;
int num;
ifstream fp("data.txt", ios::in);
fp >> num;
G = new NODE*[num];
construct_graph(G,num);
int *node_weight;
node_weight = new int[num];
depth_first_print(G, num, node_weight);
delete[]G;
return 0;
}