简体   繁体   中英

Problem with insertion in Binary Search Tree

I have written a code for insertion in Binary Search Tree and its traversal.

class node
{
public:
    int data;
    node *left;
    node *right;
};
node* createNode(int value)
{
    node *temp = new node;
    temp->data = value;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}

node *start = NULL;

void insertNode(int val)
{
    if (start == NULL)
    {
        start = createNode(val);
        return;
    }

    node *temp = start;
    while ((temp->left != NULL) && (temp->right != NULL))
    {
        if (val < temp->data)
        {
            temp = temp->left;
        }
        else if (val > temp->data)
        {
            temp = temp->right;
        }
        else
        {
            cout << "Already exists in tree\n";
            return;
        }
    }
    if (val < temp->data)
    {
        temp->left = createNode(val);
        return;
    }
    else
    {
        temp->right = createNode(val);
        return;
    }


}

void inorder(node *root)
{
    if (root != NULL)
    {
        inorder(root->left);
        printf("%d \n", root->data);
        inorder(root->right);
    }
}

It does not work fine on some test cases.

For example, if insert 15, 25 and then 35, and then traverse the tree, it only prints 15 and 25.

I am not able to find out the problem in the code. What is the issue with my insertion logic?

Let's go through the behavior -


  1. you insert the 15. if (start == NULL)
    • this check creates the start node. Now there is a start node with value 15 and left and right as NULL .

  1. you insert 25. (temp->left != NULL) && (temp->right != NULL)
    • this turns out to be false.
    • (val < temp->data) this check creates a right node.

  1. you insert 35. (temp->left != NULL) && (temp->right != NULL)
    • still turns out to be false.
    • (val < temp->data) this check creates a right node (replacing the current right node). Which is not right.

You need to correct the while loop condition here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM