当前位置:网站首页>【LeetCode】102.二叉树的层序遍历
【LeetCode】102.二叉树的层序遍历
2022-08-02 02:40:00 【酥酥~】
题目
给你二叉树的根节点 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;
}
};
边栏推荐
- 局部敏感哈希:如何在常数时间内搜索Embedding最近邻
- Reflex WMS Intermediate Series 7: What should I do if I want to cancel the picking of an HD that has finished picking but has not yet been loaded?
- 列表常用方法
- Install mysql using docker
- BI - SQL 丨 WHILE
- feign调用不通问题,JSON parse error Illegal character ((CTRL-CHAR, code 31)) only regular white space (r
- ApiFox 基本使用教程(浅尝辄止,非广)
- 架构:微服务网关(SIA-Gateway)简介
- Flask入门学习教程
- OC中成员变量,实例变量和属性之间的区别和联系
猜你喜欢
随机推荐
极大似然估计
How engineers treat open source
Safety (1)
Docker-compose安装mysql
790. 数的三次方根
详解最强分布式锁工具:Redisson
国标GB28181协议EasyGBS平台兼容老版本收流端口的功能实现
亲身经历过的面试题
240...循迹
AI target segmentation capability for fast video cutout without green screen
The principle and code implementation of intelligent follower robot in the actual combat of innovative projects
789. 数的范围
canal同步Mariadb到Mysql
罗德里格斯公式(Rodrigues‘ Rotation Formula)推导
机器人领域期刊会议汇总
The state status is displayed incorrectly after the openGauss switch
feign调用不通问题,JSON parse error Illegal character ((CTRL-CHAR, code 31)) only regular white space (r
The failure to create a role in Dahua Westward Journey has been solved
MySQL - CRUD operations
Remember a pit for gorm initialization