簡體   English   中英

二進制搜索樹刪除(C ++)

[英]Binary search tree deletion (C++)

我在C ++上實現二進制搜索樹刪除算法時遇到麻煩。 如果我嘗試刪除根目錄或直接根目錄的子目錄,則它可以正常工作。 但是它不適用於更深的級別(僅輸出同一棵樹而不刪除任何內容)。 我的代碼有什么問題?

typedef struct Node {
    int key;
    Node *left = NULL;
    Node *right = NULL;
} Node;

...

/*
 * Delete <key> from BST rooted at <node> and return modified <node>.
 */
Node* BST::pop(Node *node, int key) {
    // If <node> is a null pointer, return.
    // If <node> doesn't contain the key, traverse down the tree.
    // If <node> contains the key, perform deletion.
    if (node == NULL) {
    } else if (key < node->key) {
        node->left = pop(node->left, key);
    } else if (key > root->key) {
        node->right = pop(node->right, key);
    } else {
        // If <node> is a leaf, just delete it
        if (node->left == NULL && node->right == NULL) {
            delete node; // deallocate memory (note: node still points to a memory address!)
            node = NULL; // node points to null
        } 
        // If <node> has a single child, replace <node> with its child
        else if (node->left == NULL && node->right != NULL) {
            Node *tmp = node;
            node = node->right;
            delete tmp;
            tmp = NULL;
        } else if (node->right == NULL && node->left != NULL) {
            Node *tmp = node;
            node = node->left;
            delete tmp;
            tmp = NULL;
        } else {
            node->key = findMax(node->left);
            node->left = pop(node->left, node->key);
        }
    }
    return node;
}

int BST::findMax(Node *root) {
    if (root->left == NULL && root->right == NULL) {
        return root->key;
    } else {
        int max = root->key;
        if (root->left != NULL) {
            int leftMax = findMax(root->left);
            if (leftMax > max) {
                max = leftMax;
            }
        }
        if (root->right != NULL) {
            int rightMax = findMax(root->right);
            if (rightMax > max) {
                max = rightMax;
            }
        }
        return max;
    }
}

有兩件事:

  • 第二個if應該是else if (key > node->key)
  • 您的findMax函數異常復雜。 從某個根開始,BST中的最大值實際上只是遍歷正確的子級,直到沒有更多的正確的子級為止(因為左子樹中的任何內容都必須小於當前評估的鍵,因此leftMax永遠不能大於> max)。 因此它可能是

     int BST::findMax(Node *root) { int max = root->key; while (root->right != NULL) { root = root->right; max = root->key; } return max; } 
  • 只要樹不需要保持平衡,一般的算法就是在葉子出現的情況下刪除,如果只有一個,則交換唯一的孩子,並且在兩個孩子找到有序鄰居的情況下,交換並刪除該孩子。節點應該是健全的(不確定是否找到此鏈接,但是: http : //quiz.geeksforgeeks.org/binary-search-tree-set-2-delete/

暫無
暫無

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

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