【问题标题】:Find specific node height in tree c++在树c ++中查找特定节点高度
【发布时间】: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

标签: c++ recursion tree


【解决方案1】:

有人已经指出,但是如果您的代码到达叶子并走得更远,根据您的基本情况,它会抛出异常并退出程序。

我稍微修改了你的代码:

int treeHeight(Person* root, const string& rel_name){
    if(root == nullptr) {  
        return -1;
    }    
    else if(root->name == rel_name) return 0;

    int leftHeight = treeHeight(root->father, rel_name);
    int rightHeight = treeHeight(root->mother, rel_name);

    if (leftHeight == -1 && rightHeight == -1) {
        return -1;
    } else {
        return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
    }
}

希望对你有帮助。

【讨论】:

    【解决方案2】:

    在您的代码中,您不允许代码进入母节点,它直接来自父节点调用,因此不会提前执行。

    在下面试试这个:

    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);
        int person_height = treeHeight(root->father, rel_name, height);
        if(person_height!=0) return height;           ---------> You need to apply this check
        return treeHeight(root->mother, rel_name, height);
    }
    

    【讨论】:

    • treeHeight 函数不返回 int。所以,你代码中的这一行 - int person_height = treeHeight(root->father, rel_name, height); 是一个错误。
    • 我修复了将状态返回到 int 的问题,但它仍然返回“在抛出 'std::exception'what() 的实例后调用终止:std::exception Aborted (core dumped)”
    猜你喜欢
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多