How do you create an array of binary search trees?

Viewed 69

If I have a class for BST, would I do something like array = new BST[size] in order to create an array of BST's? Additionally, if I did end up creating an array, what would each element in the array be when it's first created?

2 Answers

Yes that would create an array, but as already said you should prefer

vector<BST> array(size);

Either way the BSTs would be default initialised. So whatever your BST default constructor does, that's what the BSTs will be.

Following code snippet may help you to understand BST Class in C++:

// C++ program to demonstrate insertion
// in a BST recursively.
#include <iostream>
using namespace std;
 
class BST {
    int data;
    BST *left, *right;
 
public:
    // Default constructor.
    BST(){
      
 
    // Parameterized constructor.
    BST(int);
 
    // Insert function.
    BST* Insert(BST*, int);
 
    // Inorder traversal.
    void Inorder(BST*);
};

// Driver code
int main()
{
    //Create array of BST:
    vectot<*BST> bstArr(10);
    for(int i = 0; i < 10; ++i){
        bstArr[i] = new BST();
    }
    
    //use bst array.
    
    return 0;
}
Related