我只是嘗試了一些代碼,而不是經驗豐富的編碼器。我實現了(至少想)Level Order遍歷,它很容易完成。想知道它是否正確的做法。二叉樹BFS的隊列
#include<iostream>
#include<queue>
using namespace std;
class node {
public :
node *right;
node *left;
int info;
}*root;
queue<int> inf;
void bfs(node *t)
{
if(t!=NULL)
{
if(t->right!=NULL)
inf.push(t->right->info);
if(t->left!=NULL)
inf.push(t->left->info);
bfs(t->right);
bfs(t->left);
}
}
int main()
{
node *temp = new node();
temp->info = 1;
root = temp;
root->right = new node();
root->right->info = 2;
root->right->right = root->right->left = NULL;
root->left = new node();
root->left->info = 3;
root->left->right = root->left->left = NULL;
node *tmp = root;
root=root->right;
root->right = new node();
root->right->info = 4;
root->right->right = root->right->left = NULL;
root->left = new node();
root->left->info = 5;
root->left->right = root->left->left = NULL;
root = tmp;
root = root->left;
root->right = new node();
root->right->info = 6;
root->right->right = root->right->left = NULL;
root->left = new node();
root->left->info = 7;
root->left->right = root->left->left = NULL;
root = temp;
node *it;
it = root;
inf.push(root->info);
bfs(root);
for(;inf.size()!=0;)
{
cout<<inf.front()<<" : ";
inf.pop();
}
return 0;
}
我明白你的意思了,我試圖在樹的基礎上打印值,即從0級[根]開始到n級[樹葉]。但是,我明白你的意思了!謝謝。 – 2012-03-24 11:37:24
@AadiDroid:是的,這就是BFS走樹的方式。每個層次又一個。但是,您正在使用DFS,並首先深入。您正在使用的隊列將稍後打印節點,而不是以不同的順序。 – LiKao 2012-03-24 13:55:44