I'm trying to create a function that returns the summary of 10 numbers inside a binary tree, for example if the user enters 1,2,3,4,5,6,7,8,9 and 10 this function returns 55. The function can be using recursion or not.
I tried different ways but the function doesn't work, here's one I tried.
int sumTree(Node* tree, int n)
{
if(tree != NULL)
{
int temp= tree->num;
return sumTree(tree->left , n + temp);
return sumTree(tree->right , n + temp);
} else {
return 0;
}
}
The Node structure is as follow
typedef struct node {
int num;
struct node *left;
struct node *right;
} Node ;
You have two return
statements, one after another. return
immediately returns from function, so return sumTree(tree->right , n + temp);
is never reached (I wouldn't be surprised if compiler decided to remove this line altogether).
You want to add values from subtrees to temp
(current node value). So return
statement you need is:
return temp + sumTree(tree->left , n + temp) + sumTree(tree->right , n + temp);
But let's get further. Second argument of function is useless in this case, delete it. And instead of creating temp variable, let's use it directly.
Summa summarum, function should look like this:
int sumTree(Node* tree)
{
if (tree != NULL) {
return tree->num + sumTree(tree->left) + sumTree(tree->right);
} else {
return 0;
}
}
Using conditional operator, you can do it in one line
int sumTree(Node* tree)
{
return tree != NULL ? tree->num + sumTree(tree->left) + sumTree(tree->right) : 0;
}
but I wouldn't actually recommend it.