103. Binary Tree Zigzag Level Order Traversal -----层序遍历
2024-09-26 06:44:18
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
] 与上一题类似
不同在于,奇数层 正着存,偶数层,倒着存。
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if(root==null) return res;
int flag =1;
queue.add(root);
while (!queue.isEmpty()) {
int levlnum = queue.size();
List<Integer> res_temp = new ArrayList<Integer>();
for (int i = 0;i<levlnum ;i++ ){ //把每层的左右节点都保存到queue里
//并讲当层的值从queue里弹出,加到res_temp 中
if(queue.peek().left!=null) queue.add(queue.peek().left);
if(queue.peek().right!=null) queue.add(queue.peek().right);
if(flag==1)
res_temp.add(queue.poll().val);
else
res_temp.add(0,queue.poll().val);
}
res.add(res_temp);
flag = 1-flag;
}
return res;
}
最新文章
- nginx配置反向代理或跳转出现400问题处理记录
- 深入学习jQuery选择器系列第四篇——过滤选择器之属性选择器
- android VelocityTracker 速度追踪器的使用及创建
- Android中Bitmap和Drawable
- nodejs笔记三--url处理、Query String;
- Jsp内置对象-session
- hibernate sql查询后对象转换成实体类
- javascript特效:会随着鼠标而动的眼睛
- NYOJ 925 国王的烦恼
- js算法集合(二) javascript实现斐波那契数列 (兔子数列)
- Xshell工具使用--连接VMware虚拟机
- ubuntu16.04系统深度学习开发环境、常用软件环境(如vscode、wine QQ、 360wifi驱动(第三代暂无))搭建相关资料
- Exp4 恶意代码分析 ——20164325王晓蕊
- intelliJ IDEA 破解,亲测有效
- MySQL数据类型和运算符
- 通过XShell实现windows文件上传到Linux服务器上
- appium -- 页面出现弹窗,关闭后,无法识别页面元素
- 安卓中使用iconfont
- 花匠(NOIP2013)(神奇纯模拟)
- apache官方供下载所有项目所有版本的官方网站地址