C ++递归不返回任何内容

时间:2019-07-15 15:27:26

标签: c++ recursion

string go(string s, int& ind, node* cur,char &c)
{
    string f = "";
    if (cur->leftChild == NULL && cur->rightChild == NULL)
    {
        f = cur-> content;
    }
    else
    {
        if (s[ind] == 0x30)
        {
            ind++;
            go(s, ind, cur->leftChild,c);
        }
        else
        {
            ind++;
            go(s, ind, cur->rightChild,c);
        }

    }
    return f;// breakpoint here shows correct value 'e'
}
...
int main()
{
   string h = "";
   int ind = 0;
   string h = go(s, ind, &glob_root,c);
   cout << h << endl; // h is blank.
}

结果是,第一次击中f点时,它会将值显示为'e',这是我想要的值,但随后的击中时它会变为空白。

如果我将其更改为

string go(string s, int& ind, node* cur,char &c)
{
    if (cur->leftChild == NULL && cur->rightChild == NULL)
    {
       return cur-> content;
    }
    else
    {
        if (s[ind] == 0x30)
        {
            ind++;
            go(s, ind, cur->leftChild,c);
        }
        else
        {
            ind++;
            go(s, ind, cur->rightChild,c);
        }

    }

}

由于我没有退货,因此我遇到访问冲突,如果我添加 返回“”; 最后,它什么也不返回,而不是'e'

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:2)

如果您在第一段代码中点击了else分支,那么什么都不会修改f,因此它当然是空的,最后返回的是空字符串。

可能想要return go(...或至少捕获返回值,并使用涉及f或直接返回它的值进行某事