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]
]
题目大意:给一个二叉树,将这个二叉树以zigzag形式输出,即一行以从左到右的顺序输出,下一行以从右到左的顺序输出……
解题思路:其实本质还是层次遍历,我们可以用cnt记录层数,奇数层从右到左,偶数层从左到右。用一个List记录这一层的数据,从左到右的顺序插入,从右到左的采用头插法插入即可。
Talk is cheap>>
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
int cnt = 0;
Deque<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if ((cnt & 0x1) == 0) {
level.add(node.val);
} else {
level.add(0, node.val);
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
res.add(level);
cnt++;
}
return res;
}