notes/CS notes/pages/Leetcode Binary-Tree-Level-Order-Traversal.md

109 lines
2.3 KiB
Markdown
Raw Normal View History

2022-07-05 09:22:08 +08:00
# Leetcode Binary-Tree-Level-Order-Traversal
#### 2022-07-05 09:09
> ##### Algorithms:
> #algorithm #BFS
> ##### Data structures:
> #DS #binary_tree
> ##### Difficulty:
> #coding_problem #difficulty-medium
> ##### Additional tags:
> #leetcode
> ##### Revisions:
> N/A
##### Related topics:
```expander
tag:#BFS
```
2022-07-05 10:48:41 +08:00
- [[Leetcode Maximum-Depth-Of-Binary-Tree]]
2022-07-05 09:22:08 +08:00
##### 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)
2022-07-05 09:44:58 +08:00
**Input:** root = `[3,9,20,null,null,15,7]`
**Output:** `[[3],[9,20],[15,7]]`
2022-07-05 09:22:08 +08:00
**Example 2:**
**Input:** root = [1]
2022-07-05 09:44:58 +08:00
**Output:** `[[1]]`
2022-07-05 09:22:08 +08:00
**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);
2022-07-05 09:44:58 +08:00
// [[ 5 ]]
2022-07-05 09:22:08 +08:00
```
### 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;
}
};
```