Code Which I have written for this :
sumBST(BST *root)
{
static sum =0;
if (root!= null)
{
if (root->left != null || root->right != null)
{
sum = sum + sumBST(root->left) + sumBST(root->right);
return sum;
}
else
{
root->data;
}
}
else
{
return 0;
}
return sum;
}
I have checked it by drawing recursion tree seems well but Still i am confused at some point I am doing some mistake. Please correct me i am doing something wrong here.
Well, it doesn’t seem like you are actually adding the sum of the leaf nodes.
In parcticular – the line:
Does not actually return the data, just reads it.
Should be something like that in pseudo code:
EDIT:
The problem in the code are as follows (clarifying and explaining further that point in the answer):
You should return the data of the leaves somewhere – this is not happening anywhere in the code – I suspect you wanted to return it in
root->data.However note that the recursion will go to each and every leaf – it is just missing returning the value from each of them.