广度优先(BFS):队列(先进先出)
void BFS(Tree *root)
{
queue<Tree *> q;
q.push<root>;
while(!q.empty())
{
root=q.front(); //访问队首元素
cout<<root->data;
q.pop(); //队首出队
if(root->lchild!=NULL)
{
q.push(root->lchild);
}
if(root->rchild!=NULL)
{
q.push(root->rchild);
}
}
}
深度优先(DFS):栈(先进后出)
void DFS(Tree *root)
{
stack<Tree *> s;
s.push(root);
while(!s.empty())
{
root=s.top(); //访问栈顶元素
cout<<root->data;
s.pop(); //弹出栈顶元素
if(root->rchild!=NULL)
{
s.push(root->rchild);
}
if(root->lchild!=NULL)
{
s.push(root->lchild);
}
}
}

本文详细介绍了图遍历中的两种核心算法:广度优先搜索(BFS)与深度优先搜索(DFS),并提供了具体的C++实现代码。通过这两种算法,可以有效地遍历图中的所有节点,适用于诸如社交网络分析、路径寻找等应用场景。
921

被折叠的 条评论
为什么被折叠?



