剑指 Offer 32 - III. 从上到下打印二叉树 III

List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> levelOrder(TreeNode root) {
        if(root == null) return res;
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        level(0, queue);
        return res;
    }

    private void level(int level,Deque<TreeNode> queue) {
        int size = queue.size();
        if(size == 0) return;
        if(level%2==0){
            List<Integer> list = new ArrayList<>();
            while (size>0){
                TreeNode node = queue.pollFirst();
                size--;
                list.add(node.val);
                if(node.left!=null) queue.addLast(node.left);
                if(node.right!=null) queue.addLast(node.right);
            }
            res.add(list);
            level++;
            level(level,queue);
        }else{
            List<Integer> list = new ArrayList<>();
            while (size>0){
                TreeNode node = queue.pollLast();
                size--;
                list.add(node.val);
                if(node.right!=null) queue.addFirst(node.right);
                if(node.left!=null) queue.addFirst(node.left);
            }
            res.add(list);
            level++;
            level(level,queue);
        }
    }

剑指 Offer 32 - III. 从上到下打印二叉树 III

 

上一篇:0437. Path Sum III (M)


下一篇:Vue第二天