题目
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
算法
public class P103 {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if (root == null) {
return list;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int length = 1;
int cur = 0;
while (!queue.isEmpty()) {
List<Integer> subList = new ArrayList<>();
for (int i = 0; i < length; i++) {
TreeNode t = queue.poll();
if (t == null) {
continue;
}
if (cur == 0) {
subList.add(t.val);
} else {
subList.add(0, t.val);
}
if (t.left != null) {
queue.add(t.left);
}
if (t.right != null) {
queue.add(t.right);
}
}
list.add(subList);
length = queue.size();
cur = 1 - cur;
}
return list;
}
}
思路:基本的层次遍历思路参见leetcode习题集——102. 二叉树的层次遍历
这里单数层和双数层用cur来控制正向反向输出。