所以我有一棵像这样的树:
class Tree{
public:
int data1;
string data2;
Animal animal;
std::list<Tree> children;
};
我正在尝试计算奇数级的data1
个节点的总和,但我无法这样做。我像这样计算所有节点的总和:
int addData1(const Tree* t, int sum){
if(t == nullptr) {
return sum;
}
else{
int temp = 0;
std::list<Tree> forest = t->children;
std::list<Tree>::iterator it;
for(it = forest.begin(); it != forest.end(); ++it){
Tree curr = *it;
temp += addData1(&curr, sum);
}
return t->data1 + temp;
}
}
但是我无法做到奇数水平,我像这样尝试过,但是总和不正确:
int addData1Odd(const Tree* t, bool odd, int sum){
if(t == nullptr){
return sum;
}
else{
int temp = 0;
std::list<Tree> forest = t->children;
std::list<Tree>::iterator it;
for(it = forest.begin(); it != forest.end(); ++it){
Tree curr = *it;
if(odd)
temp += addData1Odd(&curr, !odd, sum);
}
return t->data1 + temp;
}
}
我将不胜感激。
答案 0 :(得分:3)
如果您不在奇数水平,则停止递归。您仍然应该递归,但不要将其添加到您的总和中
编辑: 试试这个:
for(it = forest.begin(); it != forest.end(); ++it){
Tree curr = *it;
temp += addData1Odd(&curr, !odd, sum);
}
if (odd)
return t->data1 + temp;
else
return temp;