当前位置:网站首页>Question 102: sequence traversal of binary tree
Question 102: sequence traversal of binary tree
2022-07-07 05:50:00 【Yingtai night snow】
Power button 102 topic : Sequence traversal of binary tree
Title Description
Give you the root node of the binary tree root , Returns the Sequence traversal . ( That is, layer by layer , Access all nodes from left to right ).
I/o sample

Input :root = [3,9,20,null,null,15,7]
Output :[[3],[9,20],[15,7]]
Input :root = [1]
Output :[[1]]
Input :root = []
Output :[]
solution 1, Use queues to leverage iterations
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>>res;
if(!root)
{
return res;
}
// Build queue
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;
}
Solution 2 , Use recursion
vector<vector<int>>nums;
// Use recursive method to solve
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;
}
边栏推荐
- 980. 不同路径 III DFS
- I didn't know it until I graduated -- the principle of HowNet duplication check and examples of weight reduction
- 京东商品详情页API接口、京东商品销量API接口、京东商品列表API接口、京东APP详情API接口、京东详情API接口,京东SKU信息接口
- 【日常训练--腾讯精选50】292. Nim 游戏
- Preliminary practice of niuke.com (9)
- 【日常训练--腾讯精选50】235. 二叉搜索树的最近公共祖先
- STM32按键状态机2——状态简化与增加长按功能
- 谈fpga和asic的区别
- 拼多多商品详情接口、拼多多商品基本信息、拼多多商品属性接口
- zabbix_ Get test database failed
猜你喜欢
随机推荐
make makefile cmake qmake都是什么,有什么区别?
集群、分布式、微服务的区别和介绍
分布式事务介绍
微信小程序蓝牙连接硬件设备并进行通讯,小程序蓝牙因距离异常断开自动重连,js实现crc校验位
JD commodity details page API interface, JD commodity sales API interface, JD commodity list API interface, JD app details API interface, JD details API interface, JD SKU information interface
980. 不同路径 III DFS
4. 对象映射 - Mapping.Mapster
Win configuration PM2 boot auto start node project
Mysql-centos7 install MySQL through yum
消息队列:消息积压如何处理?
JSP setting header information export to excel
Cve-2021-3156 vulnerability recurrence notes
Leetcode 1189 maximum number of "balloons" [map] the leetcode road of heroding
nodejs获取客户端ip
什么是消息队列?
Digital innovation driven guide
zabbix_ Get test database failed
Pinduoduo product details interface, pinduoduo product basic information, pinduoduo product attribute interface
Flinksql read / write PgSQL
拼多多商品详情接口、拼多多商品基本信息、拼多多商品属性接口








![[PM products] what is cognitive load? How to adjust cognitive load reasonably?](/img/75/2277e0c413be561ec963b44679eb75.jpg)
