简体   繁体   English

二叉搜索树中的插入问题

[英]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.例如,如果插入 15、25 和 35,然后遍历树,它只会打印 15 和 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)你插入 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 .现在有一个值为 15 并且 left 和 right 为NULL的起始节点。

  1. you insert 25. (temp->left != NULL) && (temp->right != NULL)你插入 25. (temp->left != NULL) && (temp->right != NULL)
    • this turns out to be false.事实证明这是错误的。
    • (val < temp->data) this check creates a right node. (val < temp->data)这个检查创建一个正确的节点。

  1. you insert 35. (temp->left != NULL) && (temp->right != NULL)你插入 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). (val < temp->data)这个检查创建一个右节点(替换当前的右节点)。 Which is not right.这是不对的。

You need to correct the while loop condition here.您需要更正此处的 while 循环条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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