簡體   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