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;
}

最新文章

  1. nginx配置反向代理或跳转出现400问题处理记录
  2. 深入学习jQuery选择器系列第四篇——过滤选择器之属性选择器
  3. android VelocityTracker 速度追踪器的使用及创建
  4. Android中Bitmap和Drawable
  5. nodejs笔记三--url处理、Query String;
  6. Jsp内置对象-session
  7. hibernate sql查询后对象转换成实体类
  8. javascript特效:会随着鼠标而动的眼睛
  9. NYOJ 925 国王的烦恼
  10. js算法集合(二) javascript实现斐波那契数列 (兔子数列)
  11. Xshell工具使用--连接VMware虚拟机
  12. ubuntu16.04系统深度学习开发环境、常用软件环境(如vscode、wine QQ、 360wifi驱动(第三代暂无))搭建相关资料
  13. Exp4 恶意代码分析 ——20164325王晓蕊
  14. intelliJ IDEA 破解,亲测有效
  15. MySQL数据类型和运算符
  16. 通过XShell实现windows文件上传到Linux服务器上
  17. appium -- 页面出现弹窗,关闭后,无法识别页面元素
  18. 安卓中使用iconfont
  19. 花匠(NOIP2013)(神奇纯模拟)
  20. apache官方供下载所有项目所有版本的官方网站地址

热门文章

  1. CI框架整合微信公共平台接口
  2. number(4,2)
  3. J2EE是什么?
  4. 使用StringTokenizer分解字符串
  5. VC++ 带界面的ActiveX控件
  6. 更轻更快的Vue.js 2.0与其他框架对比(转)
  7. poj2046
  8. mvc jsonresult 前台、后台解析
  9. iOS平台iPhone和iPad免费开放源代码游戏案例列表
  10. float元素一定要闭合