输入:二叉树 root
要求:返回从上到下、从左到右的层序遍历结果
输出:vector<vector<int>>
思路:
层序遍历思路非常固定
-
使用一个队列
queue<TreeNode*> -
每次处理一层
-
本层的大小由队列当前 size 决定
-
依次将当前层节点弹出、存进结果,再把下一层节点推入队列
复杂度:
时间复杂度:O(n)
空间复杂度:O(n)
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (!root) return {};
queue<TreeNode*> q;
q.push(root);
vector<vector<int>> ans;
while (!q.empty()) {
int n = q.size();
vector<int> level;
for (int i = 0; i < n; i++) {
TreeNode* cur = q.front();
q.pop();
level.push_back(cur->val);
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
ans.push_back(level);
}
return ans;
}
};

被折叠的 条评论
为什么被折叠?



