二叉树的锯齿形层次遍历
    给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
    例如:
    给定二叉树 [3,9,20,null,null,15,7],
    3
    / \
    9 20
    / \
    15 7

    返回锯齿形层次遍历如下:
    [
    [3],
    [20,9],
    [15,7]
    ]
    解题思路:锯齿状遍历核心思想就是根据当前层数的奇偶来判断遍历后数字的顺序。因此可以采取使用两个栈的方式,根据层数判断使用哪个栈,并且根据层数判断压栈的顺序,然后将每一层的值直接出栈放入List中即可。

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. class Solution {
    11. public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    12. // 解题思路,双栈存储不同层级的值,存储时如果需要左到右,则右到左入栈,如果需要右到左,则左到右入栈
    13. // 1.创建返回结果
    14. List<List<Integer>> res = new ArrayList<>();
    15. if (root == null) {
    16. return res;
    17. }
    18. // 2.创建第一个栈,用于存储奇数层的值
    19. Stack<TreeNode> stack1 = new Stack<>();
    20. // 3.创建第二个栈,用于存储偶数层的值
    21. Stack<TreeNode> stack2 = new Stack<>();
    22. // 4.将第一个奇数层值放入栈中,即把根节点放入栈中
    23. stack1.push(root);
    24. // 5.判断当前两个栈是否均为空,均为空说明已经遍历完整个树,因为遍历过程中,stack1为空,则stack2不为空
    25. while(!stack1.isEmpty() || !stack2.isEmpty()){
    26. // 创建一个存储当前层数据的list
    27. List<Integer> list = new ArrayList<>();
    28. // 获得当前节点
    29. TreeNode cur = null;
    30. // 若第一个栈不为空,循环遍历第一个栈,把元素输出为一个list存储
    31. if(!stack1.isEmpty()){
    32. while(!stack1.isEmpty()){
    33. cur = stack1.pop();
    34. list.add(cur.val);
    35. if(cur.left!=null){
    36. stack2.push(cur.left);
    37. }
    38. if(cur.right!=null){
    39. stack2.push(cur.right);
    40. }
    41. }
    42. }else{
    43. while(!stack2.isEmpty()){
    44. cur = stack2.pop();
    45. list.add(cur.val);
    46. if(cur.right != null){
    47. stack1.push(cur.right);
    48. }
    49. if(cur.left != null){
    50. stack1.push(cur.left);
    51. }
    52. }
    53. }
    54. res.add(list);
    55. }
    56. return res;
    57. }
    58. }