当前位置:网站首页>【LeetCode】102. Level order traversal of binary tree
【LeetCode】102. Level order traversal of binary tree
2022-08-02 02:46:00 【Crispy~】
题目
给你二叉树的根节点 root ,返回其节点值的 层序遍历 . (即逐层地,从左到右访问所有节点).
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
树中节点数目在范围 [0, 2000] 内
-1000 <= Node.val <= 1000
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if(root==nullptr)
return {
};
queue<TreeNode*> myqueue;
myqueue.emplace(root);
vector<vector<int>> result;
while(!myqueue.empty())
{
result.emplace_back(vector<int>());
int len = myqueue.size();
for(int i=0;i<len;i++)
{
TreeNode* node = myqueue.front();
result.back().emplace_back(node->val);
myqueue.pop();
if(node->left)
myqueue.emplace(node->left);
if(node->right)
myqueue.emplace(node->right);
}
}
return result;
}
};
边栏推荐
猜你喜欢
随机推荐
Nanoprobes丨1-巯基-(三甘醇)甲醚功能化金纳米颗粒
使用DBeaver进行mysql数据备份与恢复
2022牛客多校四_G M
启发式合并、DSU on Tree
VPS8505 微功率隔离电源隔离芯片 2.3-6V IN /24V/1A 功率管
架构:应用架构的演进以及微服务架构的落地实践
Nacos源码分析专题(二)-服务注册
忽晴忽雨
Talking about the "horizontal, vertical and vertical" development trend of domestic ERP
53. 最小的k个数
最大层内元素和
Flask 报错:WARNING This is a development server. Do not use it in a production deployment
永磁同步电机36问(三)——SVPWM代码实现
AI target segmentation capability for fast video cutout without green screen
【web】Understanding Cookie and Session Mechanism
使用self和_(下划线)的区别
线程的不同状态
22-08-01 西安 尚医通(01)跨域配置、Swagger2、R类、统一异常处理和自定义异常、Logback日志
mysql 查看死锁
架构:微服务网关(SIA-Gateway)简介









