zoukankan      html  css  js  c++  java
  • [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();
    }
    
    
  • 相关阅读:
    【NOI2005T4】聪聪和可可-期望DP+记忆化搜索
    总结:最大权闭合子图
    【NOI2009T4】植物大战僵尸-最大权闭合子图+拓补排序
    codevs 1090 加分二叉树
    codevs 1503 愚蠢的宠物
    codevs 1992 聚会
    welcome to new life
    codevs 1066 引水入城
    codevs 2021 中庸之道
    POJ 2104 K-th Number
  • 原文地址:https://www.cnblogs.com/acbingo/p/9917217.html
Copyright © 2011-2022 走看看