# 102. Binary Tree Level Order Traversal

[Link](https://leetcode.com/problems/binary-tree-level-order-traversal/)

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:\
Given binary tree `[3,9,20,null,null,15,7]`,\\

```
    3
   / \
  9  20
    /  \
   15   7
```

return its level order traversal as:\\

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

**Solution**

Idea: 確保在代處理的queue裡面，每個node都是同一層的。每次insert下一層的東西部會影響計算上一層的東西。結論上來看queue最符合，可以先把要deque幾次記起來，之後insert的就不會被這次計算到。

T: O(N)

```
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if(root == null) return ret;
        
        queue.add(root);
        while(!queue.isEmpty()){
            List<Integer> tempResult = new LinkedList<>();
            int size = queue.size();
            for(int i = 0; i < size; i++){
                if(queue.peek().left != null) queue.add(queue.peek().left);
                if(queue.peek().right != null) queue.add(queue.peek().right);
                tempResult.add(queue.poll().val);
            }
            ret.add(tempResult);
        }
        return ret;
        
    }
}
```
