Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1848607
  • 博文数量: 184
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2388
  • 用 户 组: 普通用户
  • 注册时间: 2016-12-21 22:26
个人简介

90后空巢老码农

文章分类

全部博文(184)

文章存档

2021年(26)

2020年(56)

2019年(54)

2018年(47)

2017年(1)

我的朋友

分类: C/C++

2018-07-20 20:31:17

之前介绍过二叉树以及其相应遍历方式,连接如下:
http://blog.chinaunix.net/uid-31422160-id-5786049.html
这次写个层序遍历的,直接上代码就OK了吧~~~

点击(此处)折叠或打开

  1. struct Node{
  2.     int val;
  3.     struct Node *left;
  4.     struct Node *right;
  5.     Node(int x):val(x), left(NULL), right(NULL){}
  6. };
  7. void LevelTraverse(struct Node *root){
  8.     if(root == NULL) return;
  9.     queue<struct Node*> q;
  10.     struct Node *p;
  11.     q.push(root);
  12.     while(!q.empty()){
  13.         p = q.front();
  14.         q.pop();
  15.         cout <<p->val<<endl;
  16.         if(p->left) q.push(p->left);
  17.         if(p->right) q.push(p->right);
  18.     }
  19. }
这里用了一个辅助的队列来进行存储各个节点之间的层序关系~~
阅读(2177) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~