I have some experience with C. However I am trying out C++ and I decided to try and write some basic Tree implementations with C++. Here is how I define my TreeNode class
#include <iostream>
#include <string>
class BinaryTreeNode {
public:
int data_;
BinaryTreeNode *left_;
BinaryTreeNode *right_;
BinaryTreeNode(int d, BinaryTreeNode *l, BinaryTreeNode *r) : data_{ d }, left_{ l }, right_{ r } {}
BinaryTreeNode(int d, BinaryTreeNode *l) : data_{ d }, left_{ l }, right_{ nullptr } {}
BinaryTreeNode(int d) : data_{ d }, left_{ nullptr }, right_{ nullptr } {}
};
My Binary Search Tree class looks like,
class BST {
public:
BinaryTreeNode *head_;
void BST_Insert(BinaryTreeNode *&head, int data);
BinaryTreeNode *BST_Search(BinaryTreeNode *root, int key);
};
I wrote 2 functions which are members of the BST class. They are an insert function and a search function. My insert and search functions are,
void BST::BST_Insert(BinaryTreeNode *&head, int data) {
if (head == nullptr) {
head = new BinaryTreeNode(data);
return;
}
if (data > head->data_)
BST_Insert(head->right_, data);
else
BST_Insert(head->left_, data);
return;
}
BinaryTreeNode* BST::BST_Search(BinaryTreeNode *root, int key) {
if (root == nullptr || root->data_ == key)
return root;
if (key > root->data_)
return BST_Search(root->right_, key);
else
return BST_Search(root->left_, key);
}
In the main function I have written code to create the following tree
int main() {
BST bst;
bst.BST_Insert(bst.head_, 3);
bst.BST_Insert(bst.head_, 5);
bst.BST_Insert(bst.head_, 1);
bst.BST_Insert(bst.head_, 2);
BinaryTreeNode *oldptr = bst.head_;
BinaryTreeNode *found_1 = bst.BST_Search(bst.head_, 1);
return 0;
}
I can see that both BinaryTreeNode *oldptr = bst.head_;
and BinaryTreeNode *found_1 = bst.BST_Search(bst.head_, 1);
are causing segmentation faults to happen. Is there a way to fix this or is there an issue with my implementation?