📃 题目描述
题目链接:二叉树的层次遍历
🔔 解题思路
简简单单,用队列来保存每一层的数量,再进行遍历。
class Solution {
public:
vector> levelOrder(TreeNode* root) {
if (!root) return{};
queue que;
vector> res;
que.push(root);
while (!que.empty()) {
vector path;
int len = que.size();
for (int i = 0; i < len; i++) {
TreeNode* node = que.front();//获取值
que.pop();
path.push_back(node->val);
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
res.push_back(path);
}
return res;
}
};
💥 复杂度分析
- 空间复杂度:O(n)
- 时间复杂度:O(n)
Original: https://www.cnblogs.com/D-booker/p/16318410.html
Author: D-booker
Title: 1.层次遍历
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/604166/
转载文章受原作者版权保护。转载请注明原作者出处!