I have done an implementation of a (ADT) binary shearch tree, i had to do a function which count the number of Parents that thire sons have a difference which is less then five. the program works, only this functon fails.
at the 'return' (recursive) i got a break point.
int difference(BSTNode *root, comperFunc cmpFn, comperFunc lesserThenFive)
{
int count = 0;
if (root)
{
count = 0;
if (root->Left && root->Right)
{
//if root->Right > root->Left
if (cmpFn(root->Right->key, root->Left->key) == 1)
{
if (lesserThenFive(root->Right->key, root->Left->key))
count = 1;
}
//if root->Right < root->Left
if (cmpFn(root->Right->key, root->Left->key) == -1)
{
if (lesserThenFive(root->Left->key, root->Right->key))
count = 1;
}
}
}
return difference(root->Left, cmpFn, lesserThenFive) + difference(root- >Right, cmpFn, lesserThenFive) + count;//here is the break point
}
In your return
statement you will dereference a null pointer, if you enter difference
and root
is null.
That return needs to be inside the if
bock and you need to return some sutable value in the else
part.
To expand a bit. Your algorithm recursivley calls difference
with the left and right nodes of the current root
but eventually one of root->left
or root->right
is going to be NULL
. Your return statement will then, effectively try to call difference
with the left or right member of NULL e.g. NULL->left
. This will seg fault on any modern operating system.
User contributions licensed under CC BY-SA 3.0