首页 > 其他 > 详细

二叉树的层次遍历(BFS)

时间:2020-01-19 09:47:48      阅读:80      评论:0      收藏:0      [点我收藏+]

今日在LeetCode平台上刷到一道Medium难度的题,要求是二叉树的层次遍历。个人认为难度并不应该定在Medium, 应该是Easy比较合适,因为并没有复杂的算法逻辑,也没有corner cases

 

 

技术分享图片

 

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        //using queue
        List<List<Integer>> res= new ArrayList<>();
        if(root == null) return res;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            int len = q.size();
            List<Integer> tmp = new ArrayList<>();
            while(len-->0){
                TreeNode t = q.poll();
                tmp.add(t.val);
                if(t.left!=null) q.offer(t.left);
                if(t.right!=null) q.offer(t.right);
            }
            res.add(tmp);
        }
        return res;
    }
}

二叉树的层次遍历(BFS)

原文:https://www.cnblogs.com/zzb666/p/12210911.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!