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

    例如:
    给定二叉树 [3,9,20,null,null,15,7],

    1. 3<br /> / \<br /> 9 20<br /> / \<br /> 15 7<br />返回锯齿形层序遍历如下:

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


    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    18. List<List<Integer>> res = new ArrayList<>();
    19. if(root == null) return res;
    20. Queue<TreeNode> queue = new LinkedList<>();
    21. int cnt = 0; //层数
    22. queue.add(root);
    23. while(!queue.isEmpty()){
    24. cnt++;
    25. int n = queue.size();
    26. List<Integer> list = new ArrayList<>();
    27. while(n-- > 0){
    28. TreeNode node = queue.poll();
    29. list.add(node.val);
    30. if(node.left != null) queue.add(node.left);
    31. if(node.right != null) queue.add(node.right);
    32. }
    33. if((cnt & 1) == 0) Collections.reverse(list);
    34. res.add(list);
    35. }
    36. return res;
    37. }
    38. }