簡體   English   中英

二進制搜索樹插入數據問題

[英]Binary search tree insertion data problem

我正在嘗試實現自己的二進制搜索樹,我一直堅持插入數據,您能解釋一下我在做什么錯。

void tree::add(int data) {
    tree * tmp = new tree;

    if (root == NULL) {
        root = tmp;
        root->data = data;
        root->left = NULL;
        root->right = NULL;
    }
    else if (data <= root->data) {  
        left = tmp;
        left->data = data;
        left->left = NULL;
        left->right = NULL;

        while (tmp != NULL) {
            if (data <= left->data) {
                tmp = left->left;
            } else {
                tmp = left->right;
            }

        }
}

我正在嘗試填充左節點,如果數據i小於根,但如果數據大於此葉但仍小於根,則它應該是正確的子級,但實際上我具有訪問權限

您應該修改算法的邏輯:

//here you set the pointers to null 
left->left = NULL;
left->right = NULL;

while (tmp != NULL) {
    if (data <= left->data) {
        // here at the first time 
        tmp = left->left;
    } else {
        // or here 
        tmp = left->right;
    }
    // tmp will be set to null and the exection will end immediately
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM