二叉树的层次遍历(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;
    }
}

猜你喜欢

转载自www.cnblogs.com/zzb666/p/12210911.html