-1

由于 void 不返回任何内容,因此我不知道如何为 void 函数(如我想要获得的函数)获得适当的基本情况。

struct TreeNode {
    char value;
    TreeNode *sibling;
    TreeNode *child;
};

void serialize(std::ostream &out, TreeNode *root) 
{
    // If the root is nullptr, print "None"
    if (root == nullptr)
        out << "None" << "\n";

    // Write out root's value
    out << root->value << "\n";

    // if there is no child
    //    write out "False"
    // else
    //    write out "True"
    //    recursively call serialize on that child
    if (root->child == nullptr)
        out << false << "\n";
    else
    {
        out << true << "\n";
        serialize(out, root->child);
    }
    // recursively call serialize on the sibling
    serialize(out, root->sibling);
}

如果我将 serialize 重写为 TreeNode 类型函数会有所帮助吗?如果我这样做了,我的基本情况是什么?

注意:这是项目中的一个函数,用于在 C++ 中创建树节点数据结构。

4

1 回答 1

-2

在此代码中,您尝试递归调用 serialize 函数,但没有指定终止条件。因此每次递归函数调用都会占用栈内存,最终导致栈溢出。像 return 语句一样添加终止点,它应该可以正常工作。

 if (root == nullptr)
        out << "None" << "\n";
    return;
    

于 2018-05-01T04:06:59.573 回答