user1825608
user1825608

Reputation:

Making a template for BST class(different types of keys) in C++

I have written an implementation of BST-Tree but the key can be only string type. I would like to use that tree with other types of keys. I know that I would have to define a template, but do not know how to do it so the key will have T type. The examples show all but not important stuff.

using namespace std;
int ASCENDING = 0, DESCENDING = 1;
class Node {
public:
      string key; //I would like to change type to T
      Node* left;
      Node* right;
      Node(string key) {
            this->key = key;
            left = NULL;
            right = NULL;
      }
};

class BST {
public:
      Node* root;
      BST(string key) {
            root = new Node(key);
      }

    void insert(string value){
        if(root == NULL)
            root = new Node(value);
        else
            insertHelper(root, value);
    }

    void insertHelper(Node* node, string value){
        if(value < node->key){
            if(node->left == NULL)
                node->left = new Node(value);
            else
                insertHelper(node->left, value);
        }
        else{
            if(node->right == NULL)
                node->right = new Node(value);
            else
                insertHelper(node->right, value);
        }
    }
    void print(int order){
        show(order, root);
    }

      ~BST(){
        //delete all nodes
      }
private:
    void show(int order, Node* n){
        Node* pom = n;
        if(order == ASCENDING){
            if(pom != NULL){
                show(order, n->left);
                cout<<n->key<<endl;
                show(order, n->right);
            }
        }else{
            if(pom != NULL){
                show(order, n->right);
                cout<<n->key<<endl;
                show(order, n->left);
            }
        }

      }
};

Upvotes: 1

Views: 850

Answers (1)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158529

This should cover the basic setup and the rest of the changes should be similar:

template <typename T>
class Node {
public:
      T key; //I would like to change type to T
      ^^^^^ Type now T
      Node<T>* left;
      Node<T>* right;
      Node(T key) {
            this->key = key;
            left = NULL;
            right = NULL;
      }
};

template <typename T>
class BST {
public:
      Node<T>* root;
      ^^^^^^^ Node now will become Node<T> in the rest of the code as well
      BST(T key) {
            root = new Node<T>(key);
      }

      //  rest of code
};

Upvotes: 1

Related Questions