广度优先(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);
}
}
}