# LeetCode Binary Tree Zigzag Level Order Traversal

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,#,#,15,7}`,

3
/
9 20
/
15 7

return its zigzag level order traversal as:

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

confused what `"{1,#,2,3}"` means? >
read more on how binary tree is serialized on OJ.

OJ’s Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.

Here’s an example:

1
/
2 3
/
4

5

The above binary tree is serialized as `"{1,2,3,#,#,4,#,#,5}"`.

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if (root == null) return ans;

boolean reverse = false;
while (!queue.isEmpty()) {
List<Integer> tmp = new ArrayList<Integer>();
int num = queue.size();
for (int i = 0; i < num; i++) {
TreeNode t = queue.poll();
if (t.left != null)
if (t.right != null)
}
if (reverse) {
Collections.reverse(tmp);
reverse = false;
} else reverse = true;
}

return ans;
}
}

1. 本站所有资源来源于用户上传和网络，如有侵权请邮件联系站长！
2. 分享目的仅供大家学习和交流，您必须在下载后24小时内删除！
3. 不得使用于非法商业用途，不得违反国家法律。否则后果自负！
4. 本站提供的源码、模板、插件等等其他资源，都不包含技术服务请大家谅解！
5. 如有链接无法下载、失效或广告，请联系管理员处理！
6. 本站资源售价只是赞助，收取费用仅维持本站的日常运营所需！
7. 如遇到加密压缩包，请使用WINRAR解压,如遇到无法解压的请联系管理员！