[leetcode] 107. 二叉树的层次遍历 II

107. 二叉树的层次遍历 II

相当于把102. 二叉树的层次遍历的输出结果反转了一下

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> lists = levelOrder(root);
        Collections.reverse(lists);
        return lists;
    }
    
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) return list;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        TreeNode flag = root;
        List<Integer> nowNumList = new ArrayList<>();
        list.add(nowNumList);

        while (!queue.isEmpty()) {
            TreeNode nowNode = queue.poll();
            nowNumList.add(nowNode.val);

            TreeNode sonNode = nowNode.left;
            if (sonNode != null) queue.offer(sonNode);

            sonNode = nowNode.right;
            if (sonNode != null) queue.offer(sonNode);

            if (flag == nowNode && !queue.isEmpty()) {//判断当前元素是否为本层最后一个节点。注意要判断当处于最后一层的时候不执行,否则会添加一个空的list
                nowNumList = new ArrayList<>();
                list.add(nowNumList);
                flag = queue.peekLast();//更新标记
            }
        }
        return list;
    }
}
posted @ 2018-11-06 20:18 ACBingo 阅读(...) 评论(...) 编辑 收藏