简体   繁体   English

在树 c++ 中查找特定节点高度

[英]Find specific node height in tree c++

I am trying traverse over tree and check for specific (rel_name) and return his height, but my function traverse over "mother" branch and checks only fathers branch.我正在尝试遍历树并检查特定的(rel_name)并返回他的身高,但我的 function 遍历“母亲”分支并仅检查父亲分支。 The result is that my program return exception() and core dumping.结果是我的程序返回异常()和核心转储。 how do I fix my function to not core dump and check mothers branch too?如何修复我的 function 不进行核心转储并检查母亲分支?

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);
}

In your code, you are not allowing the code to go the mother node, its directly from the father node call and thus its not getting executed ahead.在您的代码中,您不允许代码到 go 母节点,它直接来自父节点调用,因此它不会提前执行。

Try this below:在下面试试这个:

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);
}

Someone has already pointed out, but if your code reaches a leaf and goes a little bit further, according to your base case it would throw an exception and exit the program.有人已经指出,但是如果您的代码到达叶子并走得更远,根据您的基本情况,它将引发异常并退出程序。

I revised your code a little bit:我稍微修改了你的代码:

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;
    }
}

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM