数据结构 BFS遍历树

按先序遍历创建一棵树,以层次遍历输出

样例输入

A B # D # # C E # # F # #

样例输出

LevelOrder: A B C D E F 



#include <iostream>
#include <queue>
using namespace std;

struct node {              //表示一个树上的节点
  char ch;
  node *left, *right;
};

node* creat() {               //以递归的方式构造一棵二叉树
  node *root = new node;
  char c;
  cin >> c;
  if(c == '#')  root = NULL;
  else {
    root->ch = c;
    root->left = creat();
    root->right = creat();
  }
  return root;        //返回这棵树的根节点
}

int main() {
  node *root = creat();
  queue<node*> q;
  if(root) q.push(root);
  cout << "LevelOrder:";
  while(!q.empty()) {						//用BFS的方法,层次遍历输出该二叉树
    cout << " " << q.front()->ch;
    if(q.front()->left)  q.push(q.front()->left);		//把当前节点左子树的根节点加入队列前,必须先检验当前节点是否具有左子树!!!
    if(q.front()->right)  q.push(q.front()->right);<span style="white-space:pre">		</span>//把当前节点右子树的根节点加入队列前,必须先检验当前节点是否具有右子树!!!
    q.pop();				<span style="white-space:pre">			</span>//处理完当前节点以后,就可以把它从队列中剔除了!
  }
  cout << endl;
  return 0;
}

附注:
<span style="color: rgb(51, 51, 51); font-family: arial, 宋体, sans-serif; font-size: 14px; line-height: 24px; text-indent: 28px; ">c.front() 返回容器c的第一个元素的引用。如果c为空,则该操作为空。</span>
<span style="color: rgb(51, 51, 51); font-family: arial, 宋体, sans-serif; font-size: 14px; line-height: 24px; text-indent: 28px; ">
</span>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值