无向图的深度优先生成树

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

用邻接表存储的无向图的深度优先生成树,树结点用孩子兄弟结构保存。下面是代码view plain

1.#include

2.#include

ing namespace std;

4.

5.#define MAX_VERTEX_NUM 20

6.bool visited[20];//用于遍历时辅助使用

7.bool searched[20];//用于建树时辅助使用

8.

9.//循环队列模版

10.template

11.class My_queue;

12.

13.template

14.class Node

15.{

16.private:

17. T data;

18. Node *next;

19.public:

20. Node()

21. {

22. next=0;

23. }

24. Node(T d)

25. {

26. data=d;

27. next=0;

28. }

29.friend My_queue;

30.};

31.

32.template

33.class My_queue

34.{

35.private:

36. Node *tail;

37.public:

38. My_queue()

39. {

40. tail=new Node();

41. tail->next=tail;

42. }

43.

44.bool empty()

45. {

46.return (tail->next==tail);

47. }

48.

49.void push(T d)

50. {

51. Node *p=new Node(d);

52. p->next=tail->next;

53. tail->next=p;

54. tail=p;

55. }

56.

57. T front()

58. {

59.if(empty())

60. {

61. cout<<"queue is empty!"<

62. exit(0);

63. }

64. Node *p=tail->next;

65. T data=p->next->data;

66.return data;

67. }

68.

69.void pop()

70. {

71. Node *p=tail->next;

72. Node *q=p->next;

73. p->next=q->next;

74.if(q==tail)

75. tail=p;

76.delete q;

77. }

78.};

79.

80.class ALGraph;

81.class CS_Tree;

82.//树结点

83.class CSnode

84.{

85. string data;

86. CSnode *firstchild;

87. CSnode *nextsibling;

88.friend class CS_Tree;

89.friend class ALGraph;

90.};

91.

92.//树类定义

93.class CS_Tree

94.{

95.public:

96.void PreRoot_Traverse(CSnode *T) //先根遍历

97. {

98.if(T)

99. {

100. cout<data<<" ";

101. PreRoot_Traverse(T->firstchild); 102. PreRoot_Traverse(T->nextsibling); 103. }

104. }

105.

106.void PostRoot_Traverse(CSnode *T) //后根遍历107. {

108.if(T)

109. {

110. PostRoot_Traverse(T->firstchild); 111. cout<data<<" ";

112. PostRoot_Traverse(T->nextsibling); 113. }

114. }

115.

116.void LevelOrder_Traverse(CSnode *T) //层次遍历117. {

118. My_queue q;

119. CSnode *t;

120. q.push(T);

121.do

122. {

123. t=q.front();

124.do

125. {

126. cout<data<<" ";

127.if(t->firstchild)

128. q.push(t->firstchild);

相关文档
最新文档