Sorry for this code, but I have a question.
I tried to solve a LeetCode’s 144 task. Its given that
My solution here
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root){
if(root == nullptr) return{};
vector<int> visit;
vector<TreeNode*> stack;
stack.push_back(root);
while(stack.size()){
TreeNode* vt = stack.back();
stack.erase(stack.end());
visit.push_back(vt->val);
if(vt->right!=nullptr)stack.push_back(vt->right);
if(vt->left!=nullptr)stack.push_back(vt->left);
}
return visit;
}
};
Runtime Error Message
AddressSanitizer: negative-size-param: (size=-8)
=================================================================
==20==ERROR: AddressSanitizer: negative-size-param: (size=-8)
#5 0x7f3f65eca082 (/lib/x86_64-linux-gnu/libc.so.6+0x24082)
0x602000000060 is located 8 bytes to the right of 8-byte region [0x602000000050,0x602000000058)
allocated by thread T0 here:
#4 0x7f3f65eca082 (/lib/x86_64-linux-gnu/libc.so.6+0x24082)
==20==ABORTING
but when I use stack
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root){
if(root == nullptr) return{};
vector<int> visit;
stack<TreeNode*> stack;
stack.push(root);
while(stack.size()){
TreeNode* vt = stack.top();
stack.pop();
visit.push_back(vt->val);
if(vt->right!=nullptr)stack.push(vt->right);
if(vt->left!=nullptr)stack.push(vt->left);
}
return visit;
}
};
I want use vector as a stack, but where is my mistake?
>Solution :
The statement
stack.erase(stack.end());
is wrong.
From this erase reference:
The iterator
posmust be valid and dereferenceable. Thus theend()iterator (which is valid, but is not dereferenceable) cannot be used as a value forpos.
You already have the simple and plain solution: Use an actual stack as the stack.