给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
/ \
9 20
/ \
15 7

返回其层次遍历结果:

[
[3],
[9,20],
[15,7]
]
 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> rst;
vector<int> tmpRst;
queue<TreeNode*> q;
if(root) q.push(root);
int levelcnt=;//当前层元素个数
int count=; //下一层元素个数
while(!q.empty())
{
TreeNode* Nd=q.front();
tmpRst.push_back(Nd->val);
q.pop();
--levelcnt;
if(Nd->left)
{
q.push(Nd->left);
++count;
}
if(Nd->right)
{
q.push(Nd->right);
++count;
}
if(levelcnt==)
{
levelcnt=count;
count=;
rst.push_back(tmpRst);
tmpRst.clear();
} }
return rst;
}
};

最新文章

  1. C#编程总结(十三)数据压缩
  2. CentOS 7 中设置启动模式
  3. 如何用MAT分析Android应用内存泄露
  4. 以Python角度学习Javascript(一)
  5. Cookie实例,理解cookie
  6. ubuntu10.4 server 配置VPN 安装pptp无法连接外网解决(转)
  7. 1071: [SCOI2007]组队 - BZOJ
  8. InstallShield高级应用--检查是否安装ORACLE或SQL Server
  9. 用JQuery编写textarea,input,checkbox,select
  10. gitweb安装
  11. MySql中的事务嵌套
  12. 使用HTML5的页面资源预加载(Link prefetch)功能加速你的页面加载速度
  13. 下面程序的输出结果是____ A:11,10 B:11,11 C:10,10 D:10,11 int x=10; int y=x++; printf(&quot;%d,%d&quot;,(x++,y),y++);
  14. Python代码分行问题
  15. 嵌入式Linux学习(一)
  16. mycat分库分表 mod-long
  17. 恢复Ext3下被删除的文件
  18. Elasticsearch学习之快速入门案例
  19. Github使用教程详解
  20. UITableView cell 半透明效果,改变cell高度时背景不闪的解决方法

热门文章

  1. ubuntu 18 下配置 WebStorm 编译 sass
  2. 笨办法学Python(三十八)
  3. PHP:使用php,循环html中的select标签与Php数据
  4. ABAP git客户端
  5. C++ decltype类型说明符(尾置返回类型使用)
  6. 【9.29 模拟】T3 小清新最优化(easy)
  7. 【luoguP1219】【USACO】八皇后
  8. Android学习笔记_59_清除sdcard缓存
  9. Android学习笔记_11_ListView控件使用
  10. Zookeeper watch参照表