I've implmented a basic binary search tree. Here's my node
#ifndef NODE_H
#define NODE_H
template<typename T> class node{
template<typename E> friend class bst;
public:
node():data(0), left(NULL), right(NULL){}
node(T data):data(data),left(NULL), right(NULL){}
private:
T data;
node<T>* left;
node<T>* right;
};
#endif
And here's my bst.
#ifndef BST_H
#define BST_H
template<typename T> class bst{
public:
bst():root(NULL), nodes(0){}
bst(node<T>* root):root(root), nodes(0){}
void insert(node<T>* root, const T& data){
if(root == NULL){
node<T>* root = new node<T>();
root->data = data;
nodes++;
return;
}else if(data <= root->data) {
insert(root->left, data);
}else if(data >= root->data){
insert(root->right, data);
}
}
void preorder(node<T>* root){
if(root == NULL) return;
std::cout<< root->data<<'\n';
preorder(root->left);
preorder(root->right);
}
private:
node<T>* root;
int nodes;
};
#endif
Here's the calling function
int main(){
node<int>* root = new node<int>(17);
bst<int>* t = new bst<int>(root);
t->insert(root,21);
t->insert(root,12);
t->insert(root, 9);
t->preorder(root);
delete t;
}
The output is simply 17, which is the root. I feel somehow my insert method hasn't worked right, since the preorder is a pretty standard implementation. Can somebody help me as to what is going wrong here.
Aucun commentaire:
Enregistrer un commentaire