I have written a search function in Binary Search Tree. While the function works properly and does what it should when the key is present in the tree but gives a segmentation fault when it isn't. Also is it right to print "yes" or "no" or should this function return a pointer to node?
template<class T>
class Node{
public:
T m_data;
Node<T>* m_left;
Node<T>* m_right;
Node(T data){
m_data=data;
m_left=nullptr;
m_right=nullptr;
}
};
template<class T>
class bst {
private:
Node<T>* root;
public:
bst() { root = nullptr; }
~bst() { deltree(root); }
void addnode(Node<T>* node, T data) {
if(this->root == nullptr) {
Node<T>* new_node= new Node<T>(data);
this->root = new_node;
} else if(data > node->m_data) {
if(node->m_right != nullptr) {
addnode(node->m_right, data);
} else {
Node<T>* new_node = new Node<T>(data);
node->m_right = new_node;
}
} else if(data < node->m_data) {
if(node->m_left != nullptr) {
addnode(node->m_left, data);
} else {
Node<T>* new_node = new Node<T>(data);
node->m_left = new_node;
}
}
}
void addnode(T data) { addnode(this->root, data); }
void searchkey(T data) { searchkey(data, this->root); }
void searchkey(T data, Node<T>* node) {
if(this->root == nullptr) {
std::cout << "Empty :) ";
}
if(data == node->m_data) {
std::cout << "Found";
} else if(node->m_data > data) {
searchkey(data, node->m_left);
} else if(node->m_data < data) {
searchkey(data, node->m_right);
}
else {
std::cout << "NOt fOUND";
}
}
void deltree(Node<T>* node) {
if(node) {
deltree(node->m_left);
deltree(node->m_right);
delete node;
}
};