二叉树的层次遍历(BFS)


今日在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;
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM