diff --git a/CS notes/pages/Leetcode Binary-Tree-Level-Order-Traversal.md b/CS notes/pages/Leetcode Binary-Tree-Level-Order-Traversal.md new file mode 100644 index 0000000..50b5053 --- /dev/null +++ b/CS notes/pages/Leetcode Binary-Tree-Level-Order-Traversal.md @@ -0,0 +1,108 @@ +# 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 +``` + + + +##### 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> 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> levelOrder(TreeNode *root) { + // Using queue + queue pending; + vector> 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; + } +}; +``` \ No newline at end of file