vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode *> que;
if (root != nullptr) {
que.emplace(root);
}
while (!que.empty()) {
vector<int> level;
int size = que.size();
for (int i = 0; i < size; i++) {
auto *front = que.front();
que.pop();
level.emplace_back(front->val);
if (front->left != nullptr) {
que.emplace(front->left);
}
if (front->right != nullptr) {
que.emplace(front->right);
}
}
result.emplace_back(move(level));
}
return result;
}
Problem: https://leetcode.com/problems/binary-tree-level-order-traversal/description/
Above is the function that returns a vector>.
However, since I initialized the vector as a local variable vector<vector<int>> result;
does it mean that it is a code smell for me to return it?
Since the vector is a local variable, it is allocated on the stack and the vector will get destroyed when this function call is over.
Should I have done this instead auto results = new vector<vector<int>>