简体   繁体   中英

Deleting a node from binary search tree error?

I'm trying the leetcode challenge of deleting a node in a BST. Mine deletes it but it returns a messed up tree not sure why.

struct TreeNode* deleteNode(struct TreeNode* root, int key) {

    if (root == NULL){return root;}
    else if(root->val == key){return root;}
    if(key < root->right->val){
        if( key == root->left->val){
            root->left = root->left->left;
        }
        else{
            deleteNode(root->left, key);
        }
    }
    else if( key < root->left->val){
        if ( key == root->right->val){
            root->right = root->right->right;
        }else{
            deleteNode(root->right, key);
        }
    }

    return root;
    }

You need to fix some things, and address the case where the node you are attempting to delete is the root.

Additionally, you need to fix how you update the tree when a node is deleted. You might want to consider a function that returns the minimum value node in the right sub-tree. The prototype might look something like Node *minValueNode(Node *root) .

Then when you delete a node that has two child nodes, you replace it with the minimum value node in its right sub-tree.

Consider this implementation that deals with Nodes that store strings:

TreeNode *removeWord(TreeNode *tree, char* word){
    if(tree == NULL) return tree;

    if(strcmp(tree->word, word) > 0 ){
        tree->left = removeWord(tree->left, word);
    }
    else if(strcmp(tree->word, word) < 0){
        tree->right = removeWord(tree->right, word);
    }

    else{
        if(tree->left == NULL){
            TreeNode *temp = tree->right;
            free(tree);
            return temp;
        }
        else if(tree->right == NULL){
            TreeNode *temp = tree->left;
            free(tree);
            return temp;
        }

        /* Smallest Node in the right subtree */
        TreeNode *temp = minValueNode(tree->right);

        tree->word = temp->word;
        tree->pos = temp->pos;
        tree->right = removeWord(tree->right, temp->word);
    }
    return tree;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM