# 102. Binary Tree Level Order Traversal (BFS)

BFS  Traversal



{% embed url="https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/bfs-de-shi-yong-chang-jing-zong-jie-ceng-xu-bian-l/" %}

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MCBxGJ6gRkZxuIKT6RE%2F-MCGme9rE9Mwai6ic1yr%2Fimage.png?alt=media\&token=d835c74d-f671-441d-9a0d-d7a9feb65df0)

問題點

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MCBxGJ6gRkZxuIKT6RE%2F-MCGmmDf9BSoPR4GPXOm%2Fimage.png?alt=media\&token=d424796b-115a-4984-aab1-8dbd0893f3d4)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MCBxGJ6gRkZxuIKT6RE%2F-MCGmwzUYfhS6pJV1tjl%2Fimage.png?alt=media\&token=d4fd58f1-9f90-4da3-a376-1c7e84a6ab0a)

所以需要利用當前 queue 的 size 當分層的數量

```java
/**
 * 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) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> result = new ArrayList<>();
        
        if (root == null) return result;
        
        queue.offer(root);
        
        while (!queue.isEmpty()) {
            int levelNums = queue.size();
            List<Integer> subList = new ArrayList<>();
            for (int i = 0; i < levelNums; i++) {
                
                TreeNode node = queue.poll();
                subList.add(node.val);

                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            result.add(subList);
        }
        return result;
    }
}
```
