LeetCode Binary Tree Zigzag Level Order Traversal
来源:程序员人生 发布时间:2015-05-14 09:37:38 阅读次数:2374次
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}"
.
题意:层次遍历1颗树,奇数层的时候翻转。
思路:还是利用队列层次遍历,多1个判断是不是翻转的标记就好了,还有就是java是援用传递的,所以每次都要重新声明1个对象,不然ans里面都是指向同1块内存。
/**
* 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;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
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();
tmp.add(t.val);
if (t.left != null)
queue.add(t.left);
if (t.right != null)
queue.add(t.right);
}
if (reverse) {
Collections.reverse(tmp);
reverse = false;
} else reverse = true;
ans.add(tmp);
}
return ans;
}
}
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠