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);
}
我想找到奇数偶数值节点的子树。但每轮结束后设定为0。如何总结一个的所有价值。例如,输入:1 2 3.答案应为2为(1 + 0 + 1)。但是,它返回1,这是a的最终值。我试过静态int a = 0.但它没有用。返回c将返回偶数节点的计数,而不是具有偶数值节点的奇数计数的子树。
答案 0 :(得分:1)
所以你想存储最后一个值: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