Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if (!root) {
return res;
}
queue<TreeNode*> q;
q.emplace(root);
while (!empty(q)) {
vector<int> line;
int n = size(q);
while (n--) {
TreeNode* t = q.front();
q.pop();
line.emplace_back(t->val);
if (t->left) {
q.emplace(t->left);
}
if (t->right) {
q.emplace(t->right);
}
}
res.emplace_back(line);
}
return res;
}
};