二叉树中的分段错误
要么是我盯着这段代码太久了,要么就是我无法弄清楚这一点。但是当我按降序使用 8000 数字的文本文件时; 8000, 7999, ... 我在高度函数中遇到分段错误。如果有人能看一下我会非常感激。谢谢。
int BST::height(TreeNode* node)
{
int leftSubtree = 0;
int rightSubtree = 0;
if (node == NULL)
return 0;
else
{
if (node -> getLeft() != NULL)
leftSubtree = height(node -> getLeft());
if(node -> getRight() != NULL)
rightSubtree = height(node -> getRight());
if (leftSubtree > rightSubtree)
return leftSubtree + 1;
else
return rightSubtree + 1;
}
}//ends second height
Either I've been staring at this code for way too long or I just can't figure this one out. but when I use an 8000 number text file in descending order; 8000, 7999, ... I get a segmentation fault in the height function. If someone could take a look I would be so greatful. Thanks.
int BST::height(TreeNode* node)
{
int leftSubtree = 0;
int rightSubtree = 0;
if (node == NULL)
return 0;
else
{
if (node -> getLeft() != NULL)
leftSubtree = height(node -> getLeft());
if(node -> getRight() != NULL)
rightSubtree = height(node -> getRight());
if (leftSubtree > rightSubtree)
return leftSubtree + 1;
else
return rightSubtree + 1;
}
}//ends second height
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您有一个已排序的数字列表,那么您可能会将其存储在一个列表中(树的最坏情况是 O(n),除非它是平衡的)。
在这种情况下,您的递归例程将递归 8000 次,堆栈深度为 8000。
我不知道这是否足以溢出堆栈,但无论如何您应该在中间阶段查看您的树以查看如果一切都沿着最左边的分支进行。
If you have a sorted list of numbers then you might be storing this in a list (worst case for a tree is O(n) unless it is balanced).
In this case, your recursive routine will be recursing 8000 times with a stack depth of 8000.
I don't know if this is enough to overflow the stack, but in any case you should take a look at your tree at intermediate stages to see if everything is going down the leftmost branch.