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

102. 二叉树的层次遍历

二叉树的层次遍历很简单,用队列实现bfs即可。
这里难点是要区分出每一层的楼层,分别放到对应的数组里

实际上在bfs的时候判断好在什么时候就进入了下一层即可。

设置一个标记位,用来标记当前元素是本层的最后一个元素。显然,第一层的root只有一个元素,为第一个标记。
仔细观察可以发现,下一层的最后一个元素为当前队列中最后一个元素,把标记更新即可。

class Solution {
    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;
    }
}

相比普通dfs,仅仅多出几行代码:

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

...

if (flag == nowNode && !queue.isEmpty()) {
    nowNumList = new ArrayList<>();
    list.add(nowNumList);
    flag = queue.peekLast();
}

原文地址:https://www.cnblogs.com/acbingo/p/9917217.html