题目描述

给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
image.png
得到:
[
[3],
[20, 9],
[15, 7]
]

思路

该题与102相似,唯一的不同是每一层的顺序不同,此时我们可以维持和102一样的遍历逻辑,总是从左往右访问,但是在构建每一层的数组时,根据isLeftToRight来决定是插入到数组的头部还是尾部。

代码

  1. class Solution {
  2. public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
  3. List<List<Integer>> result = new ArrayList<>();
  4. if (root == null ) {
  5. return result;
  6. }
  7. bfs(root, result);
  8. return result;
  9. }
  10. private void bfs(TreeNode root, List<List<Integer>> result) {
  11. Deque<TreeNode> queue = new ArrayDeque<>();
  12. queue.add(root);
  13. boolean isLeftToRight = true;
  14. while(!queue.isEmpty()) {
  15. int size = queue.size();
  16. List<Integer> level = new ArrayList<>();
  17. for (int i = 0; i < size; i++) {
  18. TreeNode temp = queue.pollFirst();
  19. // 与102唯一的不同在这里
  20. // isLeftToRight == true,添加到数组末尾
  21. // isLeftToRight == false,添加到数组的头部。
  22. if (isLeftToRight) {
  23. level.add(temp.val);
  24. } else {
  25. level.add(0, temp.val);
  26. }
  27. if (temp.left != null) {
  28. queue.addLast(temp.left);
  29. }
  30. if (temp.right != null) {
  31. queue.addLast(temp.right);
  32. }
  33. }
  34. result.add(level);
  35. isLeftToRight = !isLeftToRight;
  36. }
  37. }
  38. }

PS:
通过isLeftToRight来决定是pollFirst还是pollLast是错误的!!!!因为如果改变了出队顺序,那么其子结点的入队顺序也会被改变!!!