0

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.

2
  • Do you always initialize left_son and right_son to nullptr?? Commented Jun 20, 2015 at 15:47
  • @ivanw probably not, where exactly should I do this? thanks for answer btw! Commented Jun 20, 2015 at 15:53

1 Answer 1

1
 Tree *tree(int *a, int left, int right)
{
     Tree *tree1 = new Tree;
     tree1->right_son = nullptr
     tree1->left_son = nullptr

Or you could do same in the struct Tree by adding a contructor to the struct.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.