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