简体   繁体   中英

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. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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