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

问题描述 投票:0回答:2

试图编写一个程序,它将对二叉树的所有奇数元素求和。但是我的代码(函数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;
    }
c++ binary-tree
2个回答
1
投票

如果你在树中遇到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);
    }
 }

0
投票

您需要遍历树,每当找到具有奇数值的节点时,您都​​可以更新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);
}

通过引用传递root和Sum变量,在递归结束时,您将找到存储在Sum中的树的奇数值的总和。

© www.soinside.com 2019 - 2024. All rights reserved.