深度优先生成树和广度优先生成树

生成树详细介绍
关键:检测是否是第一次访问,是 则指向左孩子 不是则指向兄弟

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);
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值