0
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>>

samol
  • 18,950
  • 32
  • 88
  • 127

1 Answers1

4

No.

Since the software will not allow me to stop at that, I will elaborate. The "No" applies to the question only. I have not checked the code for errors. So, no, it is not wrong to return the result as written. There is no cost involved. Any modern compiler will use return-value optimization to return the result.

It would be very bad form to use operator new. Doing so would put the burden of deleting the object upon the calling function. Search for "C++ RAII".

Jive Dadson
  • 16,680
  • 9
  • 52
  • 65