Search code examples
c++recursionbinary-search-treeinorder

How to recursively print out all the nodes in a binary search tree using stringstream C++


I would like to print the contents of all the nodes in my binary search tree by using a stringstream and recursion. The issue is that when I use this code, only the contents of the root are displayed. I know the reason is that every time I recursively call the function InOrder(BSTNode* bst_node), my stringstream variable is created again. What can I do to my code to fix this issue while still utilizing a stringstream for output?

This is my code:

string BSTree::InOrder(BSTNode* bst_node) {
  stringstream ss;
  if (root_ ==  NULL) {
    return "";
  } else {
    if (bst_node->GetLeftChild() != NULL) {
      InOrder(bst_node->GetLeftChild());
    }
    ss << bst_node->GetContents() << " ";
    if (bst_node->GetRightChild() != NULL) {
      InOrder(bst_node->GetRightChild());
    }
  }
  return ss.str();
}

Solution

  • Something like that maybe?

    string BSTree::InOrder(BSTNode* bst_node)
    {
      if (!bst_node)
        return "";
      ostringstream ss;
      ss << InOrder(bst_node->GetLeftChild());
      ss << bst_node->GetContents() << " ";
      ss << InOrder(bst_node->GetRightChild());
      return ss.str();
    }
    

    or, you can pass around the same instance of stringstream:

    void BSTree::InOrderImpl(BSTNode* bst_node, ostringstream &ss)
    {
      if (bst_node)
      {
        InOrderImpl(bst_node->GetLeftChild(), ss);
        ss << bst_node->GetContents() << " ";
        InOrderImpl(bst_node->GetRightChild(), ss);
      }
    }
    
    string BSTree::InOrder(BSTNode* bst_node)
    {
      ostringstream ss;
      InOrder(bst_node, ss);
      return ss.str();
    }