LeetCode 102. 二叉树的层序遍历 BFS

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

这道题是一道模板题,唯一不同的是要注意对每一层元素的个数需要进行一个计数


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
               List<List<Integer>> lists = new ArrayList<>();
       if (root == null) return  lists;

        Queue<TreeNode> queue = new LinkedList<>();

        queue.add(root);


        while (!queue.isEmpty()){
            int count = queue.size();
            List<Integer> list = new ArrayList<>();
            while (count > 0){
                TreeNode temp = queue.poll();
                list.add(temp.val);

                if (temp.left!=null) queue.add(temp.left);

                if (temp.right!=null) queue.add(temp.right);

                count--;
            }
            lists.add(list);

        }

        return  lists;


    }
}



©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,887评论 1 32
  • 事件类型 - abort beforeinput click compositionend 当文本段落的组成完...
    milletmi阅读 4,955评论 0 0
  • 淅淅沥沥的雨下了一整天,温度从,20多度骤降到9度,我不得不翻出秋裤重新套上以抵御这突然的寒冷。窗外的树被风吹的哗...
    尛小小2017阅读 1,859评论 0 0
  • 朱会利 焦点讲师班五期 洛阳 坚持分享第620天《感动》2018.07.19 一直都知道公益基金会的工作...
    天天_27d6阅读 3,173评论 0 0

友情链接更多精彩内容