The program creates a binary search tree from a sorted array of numbers and adds elements to it.
struct Tree
{
Tree *left_son, *right_son;
int head, key;
};
Tree *tree(int *a, int left, int right)
{
Tree *tree1 = new Tree;
int mid = middle(left,right);
tree1->head = a[mid];
if (left != mid)
{
tree1->left_son = tree(a, left, mid-1);
}
if (right != mid)
{
tree1->right_son = tree(a, mid+1, right);
}
return tree1;
}
void add (Tree * curr_pos, int key)
{
if (key < curr_pos->head)
{
if (curr_pos->left_son != nullptr)
add (curr_pos->left_son, key);
else
{
Tree * tmp_tree = new Tree;
curr_pos->left_son = tmp_tree;
}
}
else
{
if (curr_pos->right_son != nullptr)
add (curr_pos->right_son, key);
else
{
Tree * tmp_tree = new Tree;
curr_pos->right_son = tmp_tree;
}
}
}
The problem is in line
if (curr_pos->left_son != nullptr)
, when node has no left "son", condition satisfies for some reason, but it shouldn't. I mean program finds left "son" even if there's no one, and the pointer moves there. Sorry, my english is bad, but I hope somebody can understand what I said.
Or you could do same in the struct Tree by adding a contructor to the struct.