C++:二叉树的奇数和
C++: Odd sum of values of the binary tree
正在尝试编写一个程序,对二叉树的所有奇数元素求和。但是我的代码(函数odd_sum)returns只有第一个奇数元素。我的错误在哪里?
/*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);
}
引用传递root和Sum变量,在递归结束时,你会找到Sum中存储的树的奇数之和。
正在尝试编写一个程序,对二叉树的所有奇数元素求和。但是我的代码(函数odd_sum)returns只有第一个奇数元素。我的错误在哪里?
/*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);
}
引用传递root和Sum变量,在递归结束时,你会找到Sum中存储的树的奇数之和。