函数的返回类型为void。所以例如这个语句
return sum;
没有意义。
这个 if 语句
if (root->left != NULL || root->right != NULL)
是多余的。您已经在此语句中检查过其中一个指针不等于 NULL
if (root == NULL || (root->left == NULL&& root->right == NULL))
在函数内部,它的局部变量sum也被改变了(参数是函数局部变量)。
结果这些调用
findProductSum(root->left,sum);
findProductSum(root->right,sum);
没有效果。
函数可以通过以下方式定义
long long int findProductSum( const struct node* root )
{
return root == NULL || ( root->left == NULL && root->right == NULL )
? 0ll
: root->data + findProductSum( root->left ) + findProductSum( root->right );
}
并像这样称呼
long long int sum = findProductSum( root );
其中root 是指向调用者中声明的根节点的指针。
然后就可以像这样输出得到的值了
printf( "%lld\n", sum );
这是一个演示程序
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
int insert( struct node **root, int data )
{
struct node *new_node = malloc( sizeof( struct node ) );
int success = new_node != NULL;
if ( success )
{
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
while ( *root != NULL )
{
if ( data < ( *root )->data )
{
root = &( *root )->left;
}
else
{
root = &( *root )->right;
}
}
*root = new_node;
}
return success;
}
long long int findProductSum( const struct node* root )
{
return root == NULL || ( root->left == NULL && root->right == NULL )
? 0ll
: root->data + findProductSum( root->left ) + findProductSum( root->right );
}
int main(void)
{
struct node *root = NULL;
int data[] = { 10, 15, 9, 8 };
const size_t N = sizeof( data ) / sizeof( *data );
for ( size_t i = 0; i < N; i++ ) insert( &root, data[i] );
long long int sum = findProductSum( root );
printf( "The sum of non-terminal nodes is equal to %lld\n", sum );
return 0;
}
程序输出是
The sum of non-terminal nodes is equal to 19
值为15 和8 的节点是终端节点。因此它们的值不会添加到结果总和中。