您的位置:首页 > 其它

1.层次遍历

2022-05-27 17:20 1276 查看

title: 层次遍历

📃 题目描述

题目链接:二叉树的层次遍历

🔔 解题思路

简简单单,用队列来保存每一层的数量,再进行遍历。

class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (!root) return{};
queue<TreeNode*> que;
vector<vector<int>> res;
que.push(root);
while (!que.empty()) {
vector<int> 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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: