【发布时间】:2020-07-24 23:09:48
【问题描述】:
我正在尝试遍历树并检查特定的 (rel_name) 并返回他的高度,但我的函数遍历“母亲”分支并仅检查父亲分支。 结果是我的程序返回异常()和核心转储。 如何修复我的功能以不进行核心转储并检查母亲分支?
string treeHeight(Person* root, string rel_name, int height){
height++;
if(root == nullptr) {
throw exception();
}
else if(root->name == rel_name) return to_string(height);
return treeHeight(root->father, rel_name, height);
return treeHeight(root->mother, rel_name, height);
}
【问题讨论】:
-
您的代码从根开始,首先它尽可能深入地跟随父分支。最终,通过跟随父亲分支,它到达父亲为
nullptr的叶节点,并引发程序中编写的异常。您需要扫描根下的完整树,直到找到rel_name。 -
不知道怎么实现
-
我建议您编写一些代码,从根的开头开始访问每个节点,并且它具有该节点相对于原始根的距离。如果你能写出来,你的问题就迎刃而解了。无论如何,我写了一些代码,如果你需要一些帮助 - pastebin.com/LCPKkpHX