Binary Tree Zigzag Level Order Traversal

[LeetCode]

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

Total Accepted: 44275 Total Submissions: 165753 Difficulty: Medium

Question

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).

Examples

For example:
Given binary tree {3,9,20,#,#,15,7},

     3
/ \
9 20
/ \
15 7

return its bottom-up level order traversal as:

[
[3],
[20,9],
[15,7]
]

Ways

方法一

使用队列的方法。

学习了java队列的使用。在一个队列中,放入第一个元素,取出后,放入左右孩子,再根据左右孩子逐个放入其后相应的孩子。队列为空的时候,说明已经遍历完成。

这个方法非常好,学习了。

加入标志符,根据标识符 来判断本层是否倒转

倒序算法:

    Collections.reverse(result);

方法二

使用栈的方法。

使用两个栈,一个栈放本层的节点,另外一个栈放下一层的栈。节点值加入List之后,将两个栈互换 。这个方法中要根据本层是否要倒序,判断是否颠倒加入栈中。

栈的主要方法:

    currLevel.push(root);
TreeNode node = currLevel.pop();

Solution

托管在我的GitHub上:

https://github.com/fuxuemingzhu/ZigzagLevelOrder

Captures

测试结果截图:

Reference

http://www.jiuzhang.com/solutions/binary-tree-zigzag-level-order-traversal/

Date

2015/10/14 23:34:11

最新文章

  1. pip/matplot/pandas的安装和使用
  2. ios 简单的倒计时验证码数秒过程实现
  3. 每天一个linux命令(26):du 命令
  4. Python ===if while for语句 以及一个小小网络爬虫实例
  5. keil中的串口调试:
  6. owa Your request can't be completed right now. Please try again later.
  7. gitlab ActionView::Template::Error (undefined method `[]' for nil:NilClass): 500错误
  8. CLR via C# - GC
  9. php阅读csv文件类
  10. Commix命令注入漏洞利用
  11. jsp判断为空用not empty
  12. 《XX重大技术需求征集系统》的可用性和可修改性战术分析
  13. hql- 使用like的小坑①
  14. IDEA 的黄线标注 取消
  15. php解析文本文件呈现在表格上
  16. [MySQL]group by 与 if 的统计技巧
  17. 实现instanceof关键字
  18. springboot 程序发布到tomcat运行
  19. Windows窗体数据抓取详解
  20. [转载]ASP.NET中IsPostBack详解

热门文章

  1. R包MetaboAnalystR安装指南(Linux环境非root)
  2. mysql优化方法陈列
  3. 架构B/S和C/S的区别
  4. BAT的一些题
  5. centos下Spin Version 6.3.2及ispin安装(2014.9.17)
  6. Linux文件系统属性和权限概念详解(包含inode、block、文件权限、文件软硬链接等)
  7. javaSE中级篇2 — 工具类篇 — 更新完毕
  8. Centos7服务器上RabbitMQ单机安装
  9. iOS调用系统电话、浏览器、地图、邮件等
  10. MySQL(1):SQLyog