107. 二叉树的层序遍历 II

传送门

代码

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<>();
        if(root == null) return ans;
        Stack<List<Integer>> stack = new Stack<>();
        Queue<TreeNode> que = new LinkedList<>();
        que.offer(root);
        while(!que.isEmpty()) {
            int size = que.size();
            List<Integer> list = new LinkedList<>();
            for(int i = 0;i < size; ++i) {
                TreeNode t = que.poll();
                if(t.left != null) que.offer(t.left);
                if(t.right != null) que.offer(t.right);
                list.add(t.val);
            }
            stack.add(list);
        }
        while(!stack.isEmpty()) {
            List<Integer> list = stack.pop();
            ans.add(list);
        }
        return ans;
    }
}

思路

层序遍历哪就用队列存下来每层的值,倒叙的话,就先用栈存,然后再转移一下,返回即可。