c - 如何存储变量a的值

标签 c

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/

相关文章:

c - 在 SystemV ABI 中返回一个结构

c - 套接字编程中从客户端获取char()

c - 执行 shell : wrong argument in execvp()

c - return 使指针成为整数而不进行强制转换 - 二叉树

c++ - 将 C++ 类(.cpp 文件)转换为结构体(.c 文件)

客户端随机连接到服务器

c - "C programming language"- 字符计数异常?

c - 使用 '.' token 定义常量

c - 发送 EPOLLIN 事件到 epoll_wait

c - 两个相似的程序在最后一行都有错误