当前位置:网站首页>力扣102题:二叉树的层序遍历
力扣102题:二叉树的层序遍历
2022-07-06 23:59:00 【瀛台夜雪】
力扣102题:二叉树的层序遍历
题目描述
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
输入输出样例

输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
输入:root = [1]
输出:[[1]]
输入:root = []
输出:[]
解法1,使用队列利用迭代的方式
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>>res;
if(!root)
{
return res;
}
//建立队列
queue<TreeNode *>que;
que.push(root);
vector<int>tempList;
while(!que.empty())
{
int length=que.size();
res.push_back({
});
for(int i=0;i<length;i++)
{
TreeNode * temp=que.front();
que.pop();
// cout<<temp->val<<" ";
res.back().push_back(temp->val);
if(temp->left)
{
que.push(temp->left);
}
if(temp->right)
{
que.push(temp->right);
}
}
}
return res;
}
解法二,使用递归的方式进行
vector<vector<int>>nums;
//使用递归的方法进行解决
void dns(TreeNode *root,int lever)
{
if(!root)
{
return;
}
if(nums.size()==lever)
{
nums.push_back({
});
}
nums[lever].push_back(root->val);
dns(root->left,lever+1);
dns(root->right,lever+1);
}
vector<vector<int>> levelOrder2(TreeNode* root)
{
dns(root,0);
return nums;
}
边栏推荐
- Vector and class copy constructors
- How digitalization affects workflow automation
- Reading the paper [sensor enlarged egocentric video captioning with dynamic modal attention]
- MySQL数据库学习(7) -- pymysql简单介绍
- LabVIEW is opening a new reference, indicating that the memory is full
- zabbix_get测试数据库失败
- 随机生成session_id
- 张平安:加快云上数字创新,共建产业智慧生态
- When deleting a file, the prompt "the length of the source file name is greater than the length supported by the system" cannot be deleted. Solution
- 【Shell】清理nohup.out文件
猜你喜欢

C#可空类型

Digital innovation driven guide

Zero sequence aperture of leakage relay jolx-gs62 Φ one hundred

Message queue: how to deal with message backlog?

Use Zhiyun reader to translate statistical genetics books

Leetcode: maximum number of "balloons"

JSP setting header information export to excel

1.AVL树:左右旋-bite

Record a pressure measurement experience summary

C nullable type
随机推荐
Unity keeps the camera behind and above the player
消息队列:如何确保消息不会丢失
Unity让摄像机一直跟随在玩家后上方
Leakage relay llj-100fs
Message queue: how to handle repeated messages?
《HarmonyOS实战—入门到开发,浅析原子化服务》
5阶多项式轨迹
WEB架构设计过程
Talk about mvcc multi version concurrency controller?
Digital innovation driven guide
Flinksql 读写pgsql
Flink SQL realizes reading and writing redis and dynamically generates hset key
JVM (XX) -- performance monitoring and tuning (I) -- Overview
sql优化常用技巧及理解
4. 对象映射 - Mapping.Mapster
Reading the paper [sensor enlarged egocentric video captioning with dynamic modal attention]
5. Data access - entityframework integration
Tablayout modification of customized tab title does not take effect
京东商品详情页API接口、京东商品销量API接口、京东商品列表API接口、京东APP详情API接口、京东详情API接口,京东SKU信息接口
Vector and class copy constructors