繁体   English   中英

C ++:二叉树的值的奇数和

[英]C++: Odd sum of values of the binary tree

尝试编写一个将二叉树的所有奇数元素求和的程序。 但是我的代码(函数odd_sum)仅返回第一个奇数元素。 我的错误在哪里?

/*Creating abd printing tree*/
int odd_sum(node *root)
{ if (root == NULL)  return 0;
     return root->info % 2 != 0 ? root->info:0 + odd_sum(root->left) +                     
     odd_sum(root->right);
    }

int main()
{
    int k,sum,h=0;
    node *der=tree();
    if (!der) printf ("No tree");
    else
    {
        node *root=der,*qwe=der;
        sum=odd_sum(root);
        print_tree(der,h);
        printf ("\nOdd sum :%d\n\n\n",sum);}

    return 0;
    }

如果您在树中遇到一个odd ,则只返回它的值而不分支到树上,这就是为什么只得到第一个奇数的原因。

您的代码的更正版本在以下行上:

int odd_sum(node *root){ 
    if (root == NULL) {
        return 0;
    } 
    else {
        int add = 0; 
        if(root->info % 2 != 0)  add = root->info;
        return add + odd_sum(root->left) + odd_sum(root->right);
    }
 }

您需要遍历树,每当找到具有奇数值的节点时,就可以更新Sum变量。

void oddSum(node *root, int &Sum){
      if(!root)
            return;
      if((root->val) & 1)
            Sum += root->val;

      oddSum(root->left, Sum);
      oddSum(root->right, Sum);
}

传递根和Sum变量作为参考,在递归结束时,您将找到存储在Sum中的树的奇数值之和。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM