# Leetcode Binary-Tree-Level-Order-Traversal

#### 2022-07-05 09:09

> ##### Algorithms:
>
> #algorithm #BFS
>
> ##### Data structures:
>
> #DS #binary_tree
>
> ##### Difficulty:
>
> #coding_problems #difficulty_medium
>
> ##### Additional tags:
>
> #leetcode
>
> ##### Revisions:
>
> N/A

##### Related topics:

##### Links:

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

  ***

### Problem

Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level).

#### Examples

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg)

**Input:** root = `[3,9,20,null,null,15,7]`
**Output:** `[[3],[9,20],[15,7]]`

**Example 2:**

**Input:** root = [1]
**Output:** `[[1]]`

**Example 3:**

**Input:** root = []
**Output:** []

#### Constraints

- The number of nodes in the tree is in the range `[0, 2000]`.
- `-1000 <= Node.val <= 1000`

### Thoughts

> [!summary]
> This is a #BFS problem.

In contrary to DFS, BFS uses queue. and there are many tricks for pushing 2d arrays.

```cpp
vector<vector<int>> vec;
vec.push_back({});
vec.back().push_back(5);
// [[ 5 ]]
```

### Solution

```cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode *root) {
  // Using queue
  queue<TreeNode *> pending;
  vector<vector<int>> answer;

  TreeNode *ptr = root;
  if (ptr)
    pending.push(ptr);

  while (!pending.empty()) {
    answer.push_back({});
    // After each while loop, every element in queue is in next level.
    for (int i = 0, size = pending.size(); i < size; i++) {
      ptr = pending.front();
      pending.pop();

      if (ptr->left)
        pending.push(ptr->left);
      if (ptr->right)
        pending.push(ptr->right);

      answer.back().push_back(ptr->val);
    }
  }

  return answer;
}
};
```
