LeetCode 二叉树的层次遍历 C++
2024-10-21 06:47:54
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [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;
}
};
最新文章
- C#编程总结(十三)数据压缩
- CentOS 7 中设置启动模式
- 如何用MAT分析Android应用内存泄露
- 以Python角度学习Javascript(一)
- Cookie实例,理解cookie
- ubuntu10.4 server 配置VPN 安装pptp无法连接外网解决(转)
- 1071: [SCOI2007]组队 - BZOJ
- InstallShield高级应用--检查是否安装ORACLE或SQL Server
- 用JQuery编写textarea,input,checkbox,select
- gitweb安装
- MySql中的事务嵌套
- 使用HTML5的页面资源预加载(Link prefetch)功能加速你的页面加载速度
- 下面程序的输出结果是____ A:11,10 B:11,11 C:10,10 D:10,11 int x=10; int y=x++; printf(";%d,%d";,(x++,y),y++);
- Python代码分行问题
- 嵌入式Linux学习(一)
- mycat分库分表 mod-long
- 恢复Ext3下被删除的文件
- Elasticsearch学习之快速入门案例
- Github使用教程详解
- UITableView cell 半透明效果,改变cell高度时背景不闪的解决方法