力扣103. 二叉树的锯齿形层序遍历(bfs)

class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if(root==null)return new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        queue.add(root);
        int countfanzhuan = 0;
        while(!queue.isEmpty()){
            int count = queue.size();
            List<Integer> tmp = new ArrayList<>();
            while(count>0){
                TreeNode polltree = queue.poll();
                tmp.add(polltree.val);
                if(polltree.left!=null)queue.add(polltree.left);
                if(polltree.right!=null)queue.add(polltree.right);
                count--;
            }
            if(countfanzhuan%2==1){
                Collections.reverse(tmp);
            }
            res.add(tmp);
            countfanzhuan++;
        }
        return res;
    }
}

上一篇:变量、常量的使用


下一篇:LeetCode.752 打开转盘锁的一点踩坑心得