Inorder traversal for Binary Search Tree

Hello, I am trying to print my Inorder traversal for a given BST with commas separating each name, but I always get a comma at the last name to, for example:
Ben, Jim, Nick, --> There should be no comma after Nick, it should be
Ben, Jim, Nick

My code is below and I know the issue is because I insert a comma after root->name but I have moved this comma everywhere in this small code snippet and I can not seem to find a way to get the output correct


1
2
3
4
5
6
7
8
9
10
11
12
13
// Inorder
void printInorder(node* root)
{
    if (root == nullptr)
        cout << "";
    else
    {
        printInorder(root->left);
        cout << root->name << ", ";
        printInorder(root->right);
    }
}
Presumably, there is no comma at all if the tree has a single node.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void printInorder(node* root, int &numSeen)
{
    if (root == nullptr)
        cout << "";
    else
    {
        printInorder(root->left,numSeen);
        if ( numSeen++ > 0 ) cout << ", ";
        cout << root->name;
        printInorder(root->right,numSeen);
    }
}

.. 
int n = 0;
printInorder(mytree,n);

Unfortunately my output prints as Ben , , Nick, Jim, ,
Post a minimal compilable example that we can test with.
I don't have time to write an entire test just for this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
using namespace std;

template <typename T> class tree
{
   class node
   {
   public:
      T data;
      node *left = nullptr, *right = nullptr;
      node( T v ) : data( v ){}
   };

   node *root = nullptr;
   bool first = true;

public:
   void insert( T value ){ insert( root, value ); }
   void output()         { first = true;   output( root );    cout << '\n'; }

private:
   void insert( node *&ptr, T value );
   void output( node *ptr );
};

template<typename T> void tree<T>::insert( node *&ptr, T value )
{
   if ( !ptr ) ptr = new node( value );
   else if ( value < ptr->data ) insert( ptr->left , value );
   else if ( value > ptr->data ) insert( ptr->right, value );
}

template<typename T> void tree<T>::output( node *ptr )
{
   if ( ptr )
   {
      output( ptr->left );
      if ( !first ) cout << ", ";
      cout << ptr->data;
      first = false;
      output( ptr->right );
   }
}

//=================================================================

int main()
{
   tree<string> T;
   for ( string s : { "Doc", "Grumpy", "Happy", "Sleepy", "Bashful", "Sneezy", "Dopey" } ) T.insert( s );
   T.output();
}


Bashful, Doc, Dopey, Grumpy, Happy, Sleepy, Sneezy
Topic archived. No new replies allowed.