繁体   English   中英

二叉搜索树中的插入问题

[英]Problem with insertion in Binary Search Tree

我已经编写了一个用于在二叉搜索树中插入及其遍历的代码。

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);
    }
}

在某些测试用例上它不能正常工作。

例如,如果插入 15、25 和 35,然后遍历树,它只会打印 15 和 25。

我无法找出代码中的问题。 我的插入逻辑有什么问题?

让我们来看看行为 -


  1. 你插入 15. if (start == NULL)
    • 此检查创建起始节点。 现在有一个值为 15 并且 left 和 right 为NULL的起始节点。

  1. 你插入 25. (temp->left != NULL) && (temp->right != NULL)
    • 事实证明这是错误的。
    • (val < temp->data)这个检查创建一个正确的节点。

  1. 你插入 35. (temp->left != NULL) && (temp->right != NULL)
    • 结果仍然是假的。
    • (val < temp->data)这个检查创建一个右节点(替换当前的右节点)。 这是不对的。

您需要更正此处的 while 循环条件。

暂无
暂无

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

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