简体   繁体   English

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

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

Trying to write a program which will sum all odd elements of binary tree. 尝试编写一个将二叉树的所有奇数元素求和的程序。 But my code (function odd_sum) returns only first odd element. 但是我的代码(函数odd_sum)仅返回第一个奇数元素。 Where is my mistake? 我的错误在哪里?

/*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;
    }

If you meet an odd value in the tree you are just returning its value without branching down the tree, that's why you get only the first odd number. 如果您在树中遇到一个odd ,则只返回它的值而不分支到树上,这就是为什么只得到第一个奇数的原因。

The corrected version of your code is on the line of: 您的代码的更正版本在以下行上:

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);
    }
 }

You need to traverse down the tree and whenever you find the node with odd value you can update your Sum variable. 您需要遍历树,每当找到具有奇数值的节点时,就可以更新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);
}

Pass the root and Sum variable with reference, at the end of the recursion, you will find the sum of the odd values of tree stored in Sum. 传递根和Sum变量作为参考,在递归结束时,您将找到存储在Sum中的树的奇数值之和。

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

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