请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

 

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

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

 

提示:

  1. 节点总数 <= 1000
Related Topics
  • 广度优先搜索
  • 二叉树

  • 👍 186
  • 👎 0
  • 接上文JAVA BFS 3 连发(2),的从上到下打印二叉树 II
    一层正序、一层倒序的话,也好办、一层正向往Integer[] line里填,下一层逆向往Integer[] line里填就可以了

    代码

    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            boolean flag = true;
            Queue<TreeNode> queue = new LinkedList<>();
            if (null!=root)queue.offer(root);
            while (!queue.isEmpty()){
                int size = queue.size();
                flag = !flag;
                Integer[] line = new Integer[size];
                while (size-- > 0){
                    if (null != queue.peek().left)queue.offer(queue.peek().left);
                    if (null != queue.peek().right)queue.offer(queue.peek().right);
                    if (flag) {
                        line[size] = queue.poll().val;
                    }else{
                        line[line.length-size-1] = queue.poll().val;
                    }
                }
                res.add( Arrays.asList(line));
            }
            return res;
        }
    
    }
    

    BFS相关合集

    BFS三连发1

    BFS三连发2

    BFS三连发3