如何获取列表中有子节点的树的节点总和?
How to get sum of nodes of a tree which has children in a list?
所以我有一棵树是这样的:
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;
}
}
如有任何帮助,我将不胜感激。
如果你不在奇数层,你就停止递归。您仍然应该递归,但不要将其添加到您的总和
编辑:
试试这个:
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;
所以我有一棵树是这样的:
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;
}
}
如有任何帮助,我将不胜感激。
如果你不在奇数层,你就停止递归。您仍然应该递归,但不要将其添加到您的总和
编辑: 试试这个:
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;