英文:
Zigzag traversal, c++, Runtime error : Abort signal from abort(3) (SIGABRT), bad memory allocation
问题
代码出现运行时错误,Abort signal from abort(3) (SIGABRT)。我无法找到错误,请求帮助。
英文:
Zigzag traversal, c++, Runtime error : Abort signal from abort(3) (SIGABRT), bad memory allocation
class Solution {
public:
void solve(Node* root, vector<int>& v, int i)
{
if (root == NULL) {
return;
}
stack<Node*> ms;
stack<Node*> cs;
ms.push(root);
while (ms.empty() == false) {
Node* curr = ms.top();
ms.pop();
v.push_back(curr->data);
if (i % 2 != 0) {
if (curr->left != NULL) {
cs.push(root->left);
}
if (curr->right != NULL) {
cs.push(root->right);
}
}
if (i % 2 == 0) {
if (curr->right != NULL) {
cs.push(root->right);
}
if (curr->left != NULL) {
cs.push(root->left);
}
}
if (ms.empty()) {
cs.swap(ms);
++i;
}
}
}
//Function to store the zig zag order traversal of tree in a list.
vector<int> zigZagTraversal(Node* root)
{
// Code here
vector<int> v;
int i = 1;
solve(root, v, i);
return v;
}
};
The code is giving run time error as ,
Runtime error : Abort signal from abort(3) (SIGABRT).
I am not able to find the mistake , pls help me out.
答案1
得分: 1
请按照其他人的建议在下次发布时执行以下操作:
- 解释代码的预期功能;
- 创建一个MVP(最小可行产品);
- 尝试在本地进行调试。
你的问题在于:
你陷入了一个无限循环,因为你总是添加根节点的子节点,而不是当前节点的子节点。
你的解决方案是:
在所有四个地方,cs.push(root->left);
应该改为 cs.push(curr->left);
。 (在适当的情况下用 right
替换 left
。)
为了避免下次发生:
使用全词变量名称,如 current
,而不是 curr
。这样你就不太可能将其与看起来相似的东西弄混,比如 root
。
命名是一个最困难的问题之一,它会导致像你遇到的这个错误。
英文:
The next time you post, please do what the others suggested:
- explain what the code is expected to do;
- create an MVP;
- try to debug locally;
Your problem is this:
You have an infinite loop, because you're always adding the children of the root, rather than the children of the current node.
Your solution is this:
cs.push(root->left);
should be cs.push(curr->left);
in all four places. (Replace left with right, where appropriate.)
To avoid next time:
Use full words as variable names, like current
, instead of curr
. Then you'll be less likely to mix it up with something that looks similar, like root
.
Naming is one of the hardest problems, and it leads to many mistakes like the one you had.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论