生成树详细介绍
关键:检测是否是第一次访问,是 则指向左孩子 不是则指向兄弟
void MGraph::DFSTree(int i, CSTree&T){
//将正在访问的该顶点的标志位设为true
visited[i] = true;
bool first = true;
CSTree q = NULL;
//依次遍历该顶点的所有邻接点
for (int w = FirstAdj(i); w >= 0; w = NextAdj(i,w)){
//如果该临界点标志位为false,说明还未访问
if (!visited[w]) {
//为该邻接点初始化为结点
CSTree p = new CSNode(this->vexs[w]);
//该结点的第一个邻接点作为孩子结点,其它邻接点作为孩子结点的兄弟结点
if (first) {//第一次访问该结点,都是左孩子
T->lchild = p;
first = false;
}
//否则,为兄弟结点
else{
q->nextsibling = p;
}
q = p;
//以当前访问的顶点为树根,继续访问其邻接点
DFSTree(w, q);
}
}
}
void MGraph::DFSFrost(){
cout << "深度生成森林" << endl;
if (this->tree != NULL)
this->deleteFrost();
CSTree q = NULL;
for (int i = 0; i < this->vexnum; i++){
if (visited[i]==false){
CSTree p = new CSNode(this->vexs[i]);
if (this->tree == NULL)
tree = p;
else
q->nextsibling = p;
q = p;
DFSTree(i, q);
}
}
}
void MGraph::BFSTree(int i,CSTree&T){
queue<CSTree>q;//这里要存储CSTree 不能再存储下标
//因为要使用队列中的CSTree 来选择连接lchild还是nextsibling
q.push(T);
CSTree temp = NULL;
CSTree p = NULL;
CSTree t = NULL;
visited[i] = true;
while (!q.empty())
{
bool first = true;
t = q.front();
q.pop();
int n = LocateVex(t->data);
for (int w = FirstAdj(n); w >= 0; w = NextAdj(n, w)){
visited[w] = true;
p = new CSNode(vexs[w]);
q.push(p);
if (first){
t->lchild = p;
first = false;
}
else
temp->nextsibling = p;
temp = p;
}
}
}
void MGraph::BFSFrost(){
cout << "广度生成森林" << endl;
if (this->tree != NULL)
this->deleteFrost();
CSTree q =NULL;
for (int i = 0; i < this->vexnum; i++){
if (!visited[i]){
CSTree p = new CSNode(vexs[i]);
if (!this->tree)
tree = p;
else
q->nextsibling = p;
q = p;
BFSTree(i, q);
}
}
}