当前位置:网站首页>力扣刷题——二叉树的层序遍历Ⅱ
力扣刷题——二叉树的层序遍历Ⅱ
2022-06-11 18:14:00 【HHYX.】
题目链接:二叉树的层序遍历Ⅱ
题目描述
给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
题目分析
这里题目看上去很难,如果将二叉树自底向上进行遍历,似乎很难做到。但是不妨换个思路,如果将二叉树从上而下遍历形成的二维数组逆置,是否就相当于自底向上的遍历了。这样一来,思路就很清楚了。二叉树的正常层序遍历方法可以参考上一篇博客,这里就不多介绍了,这里只需要将最后结果进行逆置即可通过,代码如下:
代码实现
vector<vector<int>> levelOrderBottom(TreeNode* root)
{
vector<vector<int>> ret;
queue<TreeNode*> q;
if (root)
{
q.push(root);
}
int levelsize = q.size();
while (!q.empty())
{
vector<int> tmp;
while (levelsize)
{
TreeNode* cur = q.front();
q.pop();
tmp.push_back(cur->val);
if (cur->left)
{
q.push(cur->left);
}
if (cur->right)
{
q.push(cur->right);
}
levelsize--;
}
ret.push_back(tmp);
levelsize = q.size();
}
reverse(ret.begin(), ret.end());
return ret;
}

边栏推荐
- 初识企业级平台
- 了解一下random库·1
- 牛客刷题——part8
- 高性能架构设计
- Use egg Js+mongodb simple implementation of curdapi
- Easycwmp source code analysis
- Some problems of DC-DC bootstrap capacitor
- Monitoring loss functions using visdom
- ACL 2022:评估单词多义性不再困扰?一种新的基准“DIBIMT”
- ACL 2022: is it no longer difficult to evaluate word polysemy? A new benchmark "dibimt"
猜你喜欢

NFT platform development NFT mall source code NFT mall development chain game development

New work of "the father of LSTM": a new method towards self correcting neural network

平衡搜索二叉树——AVL树

Ubuntu installs PSQL and runs related commands

Jsfinder, wafw00f installation, nmap configuration (msvcr120.dll file is missing)
![[golang] leetcode - 292 Nim games (Mathematics)](/img/82/54c3f6be9d08687b42cba0487380f0.png)
[golang] leetcode - 292 Nim games (Mathematics)

SISO Decoder for SPC (补充章节1)

Common interview questions of network and concurrent programming

NR LDPC 打孔-punctured

Say no to credit card fraud! 100 lines of code to realize simplified real-time fraud detection
随机推荐
HashSet集合存储学生对象并遍历
Class question: how to ensure that line table storage can be inserted at any time?
[C语言]用结构体按分数高低降序输出学生的姓名和分数
LDAP 目录服务器的现代化应用
Oracle高级数据库复习
Surveillance des fonctions de perte avec visdom
牛客刷题——求最小公倍数
Codeworks round 481 (Div. 3) [done]
系统的可扩展型
ACL 2022:评估单词多义性不再困扰?一种新的基准“DIBIMT”
MATLAB 保存imshow绘制图片到指定文件夹中的两种方法
On the problem that the while loop condition in keil does not hold but cannot jump out
Is it good or not to open a stock account on the flush? Is it safe?
Feign 共享登录信息进行请求
新项目 搭建环境方法
EditText amount limit
General terms in security field
软件需求工程复习
Database lock and transaction isolation level
炫酷的可视化工具:processing 初识