2.2 KiB
2.2 KiB
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:
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:
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.
vector<vector<int>> vec;
vec.push_back({});
vec.back().push_back(5);
// [[ 5 ]]
Solution
/**
* 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;
}
};