int countRec(struct TreeNode* root)
{
int a = 0;
int c = countRec(root->left);
c += countRec(root->right);
if(root->data % 2 == 0)
c += 1;
if (c % 2 != 0)
a++;
return a;
}
int CountSubTrees(struct TreeNode *root)
{
if(root==NULL)
return -1;
return countRec(root);
}
我想找到具有奇数个偶值节点的子树。但每轮结束后 a 都会设置为 0。如何求a的所有值的总和。例如,输入:1 2 3。答案应为 2,即 (1 + 0 + 1)。但是,它返回 1,这是 a 的最终值。我尝试了 static int a = 0. 但它不起作用。返回 c 将返回偶数节点的计数,而不是具有偶数值节点奇数的子树。
最佳答案
所以你想存储最后一个值:a
你必须用你的代码片段创建一个函数,如下所示
int calculate_a()
{
int a = 0;
int c = countRec(root->left);
c += countRec(root->right);
if(root->data % 2 == 0)
c += 1;
if (c % 2 != 0)
a++;
return a;
}
然后在你的主要内容或类似的内容中
int main()
{
int my_var = calculate_a();
}
你的变量 a 将存储在 my_var
关于c - 如何存储变量a的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48583795/