【问题标题】:Problem with insertion in Binary Search Tree二叉搜索树中的插入问题
【发布时间】:2019-04-17 06:21:17
【问题描述】:

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

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。

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

【问题讨论】:

  • 你 while 条件不正确.. 调试它并查看你当前的树结构以及为什么 while 正文会被跳过它不应该的地方

标签: c++ binary-tree binary-search-tree dynamic-programming


【解决方案1】:

让我们来看看行为 -


  1. 你插入 15。if (start == NULL)
    • 此检查创建起始节点。现在有一个值为 15 的起始节点,左右为NULL

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

  1. 你插入 35。(temp-&gt;left != NULL) &amp;&amp; (temp-&gt;right != NULL)
    • 仍然证明是错误的。
    • (val &lt; temp-&gt;data) 这个检查会创建一个右节点(替换当前的右节点)。 这是不对的。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多