1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74struct Node
{
int id;
int childNum;
Node* childList[10];
};
struct Queue
{
Node* list[100];
int front;
int rear;
int num;
};
void InitQueue(Queue &q)
{
q.front = q.rear = 99;
q.num = 0;
}
int EnQueue(Queue &q,Node* n)
{
if (q.num == 100) return -1;
q.rear = (q.rear+1)%100;
q.list[q.rear] = n;
q.num = q.num+1;
return 1;
}
int DeQueue(Queue &q,Node* &n)
{
if (q.num == 0) return -1;
q.front = (q.front+1)%100;
n = q.list[q.front];
q.num = q.num-1;
return 1;
}
int main()
{
int i;
Node* tree;
tree = (Node*)malloc(sizeof(Node));
tree->id = 1;
tree->childNum = 3;
for (i=1;i<=tree->childNum;i++)
{
tree->childList[i-1] = (Node*)malloc(sizeof(Node));
tree->childList[i-1]->id = i+1;
tree->childList[i-1]->childNum = 0;
}
tree->childList[0]->childNum = 2;
tree->childList[0]->childList[0] = (Node*)malloc(sizeof(Node));
tree->childList[0]->childList[0]->id = 5;
tree->childList[0]->childList[0]->childNum = 0;
tree->childList[0]->childList[1] = (Node*)malloc(sizeof(Node));
tree->childList[0]->childList[1]->id = 6;
tree->childList[0]->childList[1]->childNum = 0;
Queue q;
InitQueue(q);
EnQueue(q,tree);
while(q.num!=0)
{
Node* n;
DeQueue(q,n);
cout<id<<' '; if (n->childNum!=0)
{
for (i=0;ichildNum;i++) EnQueue(q,n->childList[i]);
}
}
cout<<endl;
return 0;
}
输出为:1 2 3 4 5 6