当前位置:网站首页>JZ59.按之字型顺序打印二叉树
JZ59.按之字型顺序打印二叉树
2022-06-21 16:53:00 【SS_zico】
牛客:JZ59
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
示例1
输入
{8,6,10,5,7,9,11}
返回值
[[8],[10,6],[5,7,9,11]]
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ret;
if (!pRoot) return ret;
queue<TreeNode*> q;
q.push(pRoot);
int level = 0;
while (!q.empty()) {
int sz = q.size();
vector<int> ans;
while (sz--) {
TreeNode *node = q.front();
q.pop();
ans.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
++level;
if (!(level&1)) // 偶数层 反转一下
reverse(ans.begin(), ans.end());
ret.push_back(ans);
}
return ret;
}
};
边栏推荐
- 基本文件操作
- Use of list
- TypeScript的类型检查
- EtherCAT object dictionary analysis
- [real topic of the Blue Bridge Cup provincial tournament 35] scratch water reflection children's programming scratch programming explanation of the real topic of the Blue Bridge Cup provincial tournam
- 力扣141.环形链表
- 【微服务|Nacos】快速实现nacos的配置中心功能,并完成配置更新和版本迭代
- I got a pay cut in disguise
- 基于AM4377的EtherCAT主站控制stm32从站
- 科普大佬说 | 如何打造自己的AI创造力?
猜你喜欢

Zhong'an insurance, together with Alibaba health and huiyitianxia, explores a new model of Internet chronic disease management

在线文档协作:办公必备高效率神器

Server socket program

原码、补码、反码的关系

How to create your own AI creativity?

大型网站技术架构 | 信息加密技术及密匙安全管理

Basic file operation

小程序的宿主环境、组件、API、协同工作和发布
![[technical management] assembly number and sword team](/img/80/4b39d98c7b51c6c50a4cd5f0a38370.jpg)
[technical management] assembly number and sword team

EtherCAT igh主站控制3个台达asdaa2伺服转圈圈
随机推荐
CentOS使用composer install 报错 - phpunitphpunit 8
缓存型数据库Redis的配置与优化
EtherCAT igh 'Fatal Sync Error'——0x002C,0x001A
STM32F1与STM32CubeIDE编程实例-线性霍尔效应传感器驱动
Redis6.0 new features (Part 1)
[real topic of the Blue Bridge Cup provincial tournament 35] scratch water reflection children's programming scratch programming explanation of the real topic of the Blue Bridge Cup provincial tournam
雷军的千亿失误?
C language DLL Dynamic Link Library
Typescript的通用类型检查
PHP输出函数
论文笔记 ACL 2022|Unified Structure Generation for Universal Information Extraction
I got a pay cut in disguise
Node的字符处理
现有需求同步其他数据库用户信息到我们系统他们主键id为string我们主键为Long
What is the S3 protocol that we are talking about every day? This article takes you to understand the story behind S3
Paper notes ACL 2022 unified structure generation for universal information extraction
aws elastic beanstalk入门之简介
POSIX create terminate thread
Typescript的构造方式
信创环境下缓存服务Redis集群部署