二叉搜索树删除(C ++)

时间:2017-01-24 04:35:16

标签: c++ data-structures binary-search-tree

我在C ++上实现二叉搜索树删除算法时遇到了麻烦。如果我尝试删除root或root的子项,它可以正常工作。但它不适用于更深层次(只输出相同的树而没有任何删除)。我的代码出了什么问题?

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

1 个答案:

答案 0 :(得分:0)

有几件事:

  • 其他如果应该是else if (key > node->key)
  • 您的findMax函数异常复杂。来自某个根的BST中的最大值实际上只是遍历正确的子项,直到没有更多正确的子项(因为左子树中的任何内容必须小于您当前正在评估的键,因此leftMax永远不会是&gt; 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/