Segmentation fault in a Binary Tree
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
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.
精彩评论