-1

Since void doesn't return anything, I don't know how to get a proper base case for a void function like the one I am trying to get.

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

Would it help if I rewrite serialize as a TreeNode type function instead, what would be my base case if I did that?

Note: this is one function from a project to create a tree-node data structure in c++.

Neezo
  • 9
  • 3
  • I'm curious as to why your `TreeNode` stores a pointer to a *child* and *sibling*... What kind of tree is that? – WhiZTiM May 01 '18 at 03:58
  • 1
    write, then return. – Joseph D. May 01 '18 at 03:58
  • Think about these: What does and what can your function do when `root == nullptr`? What does and what can it do when `sibling == nullptr`? –  May 01 '18 at 04:00
  • @WhiZTiM, probably a graph. – Joseph D. May 01 '18 at 04:00
  • @WhiZTiM The simplest way of implementing a `*`-ary tree in C or assembly? – aschepler May 01 '18 at 04:02
  • First, it seems your code have a bug - if root is nullptr, the code prints None then falls through to dereference it in the 6th and 13th lines. As Raja Babu Prasad wrote, you should either add return or put the rest of the code in an else block. Second, this is a recursive function. The larger the tree, the more stack it would consume. If the tree is large enough, it would cause a stack overflow. The alternative is to use an std::stack (allocated on the heap) and rewrite the function to push & pop the sibling & child pointers on it, making it iterative rather than recursive. – Uri Raz May 01 '18 at 05:35

1 Answers1

-2

In this code you are trying to call the serialize function recursively, but there is no termination condition specified. therefore as a result of which each time the recursive function-call the stack memory is occupied, eventually leading to stack overflow. Add the termination point like the return statement, it should work fine.

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