广度优先搜索

#include<iostream>
#include<vector>
#include<stack>
#include<string>
#include<queue>
#include<algorithm>
#include<numeric>
using namespace std;

class node{
public:
    int val;
    node* left;
    node* right;
    node():val(0),left(NULL),right(NULL){}
};

node* createTree()
{
    node* head = new node[14];
    for(int i = 0;i<10;i++)
    {
        head[i].val = i;
        if(2*i+1 < 10)
        head[i].left = head + 2*i + 1;
        if(2*i+2 < 10)
        head[i].right = head + 2*i + 2;
    }
    return head;
}

void GFS(node* root)
{
  node* r = root;
  queue<node*> q;
  q.push(root);
  while(!q.empty())
  {
      node* temp = q.front();
      cout<<temp->val<<" ";
      q.pop();
      if(temp->left != NULL)
      q.push(temp->left);
      if(temp->right != NULL)
      q.push(temp->right);
  }
}

int main()
{
    node* t = createTree();
    GFS(t); cout<<endl;
}

 

posted on 2014-05-22 20:40  berkeleysong  阅读(102)  评论(0编辑  收藏  举报

导航