Problem: 102. 二叉树的层序遍历
文章目录
- 题目描述
- 思路
- 复杂度
- Code
题目描述
思路
直接套用树的层序遍历模板,同时将每一层的节点存入一个数组中,并将其存入最终的二维结果数组中
复杂度
时间复杂度:
O ( n ) O(n) O(n);其中 n n n为树节点的个数
空间复杂度:
O ( n ) O(n) O(n)
Code
/**
* 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:
/**
* BFS
* @param root The root of the binary tree
* @return vector<vector<int>>
*/
vector<vector<int>> levelOrder(TreeNode *root) {
if (root == nullptr) {
return vector<vector<int>>();
}
vector<vector<int>> res;
queue<TreeNode *> tmp;
tmp.push(root);
while (!tmp.empty()) {
vector<int> level;
int curLeveSize = tmp.size();
for (int i = 0; i < curLeveSize; i++) {
TreeNode *node = tmp.front();
tmp.pop();
level.push_back(node->val);
if (node->left != nullptr) {
tmp.push(node->left);
}
if (node->right != nullptr) {
tmp.push(node->right);
}
}
res.push_back(level);
}
return res;
}
};