Possible solution


  • 0
    L

    So I am trying to delete 33 from the following tree:

    0_1478540313251_Screen Shot 2016-11-07 at 9.37.48 AM.png

    Here is my result:

    0_1478540376540_Screen Shot 2016-11-07 at 9.37.26 AM.png

    Why it is not a possible result?


  • 0

    Looks ok. Show your code?


  • 0
    L

    class Solution {
    public:
    TreeNode* deleteNode(TreeNode* root, int key) {
    if (root != NULL) {
    if (root->val < key) {
    root->right = deleteNode(root->right, key);
    }
    else if (root->val > key) {
    root->left = deleteNode(root->left, key);
    }
    else {
    if (root->right != NULL) {
    root->val = minNode(root->right, root);
    }
    else {
    TreeNode* temp = root;
    root = root->left;
    delete temp;
    }
    }
    }
    return root;
    }

    int minNode(TreeNode* root, TreeNode* parent) {
        if (root->left != NULL) {
            return minNode(root->left, root);
        }
        else {
            int found = root->val;
            if (parent->left == root) {
                parent->left = root->right;
            }
            else {
                parent->right = root->right;
            }
            delete root;
            return found;
        }
    }
    

    };


  • 0
    I

    @lawchihon where did the node 37 come from in the output image? I can't seem to find it in the input.


  • 0
    L

    @ironmissy Because the complete input for this is:

    [2,0,33,null,1,25,40,null,null,11,31,34,45,10,18,29,32,null,36,43,46,4,null,12,24,26,30,null,null,35,39,42,44,null,48,3,9,null,14,22,null,null,27,null,null,null,null,38,null,41,null,null,null,47,49,null,null,5,null,13,15,21,23,null,28,37,null,null,null,null,null,null,null,null,8,null,null,null,17,19,null,null,null,null,null,null,null,7,null,16,null,null,20,6]
    33

    So my solution has the result:

    [2,0,34,null,1,25,40,null,null,11,31,36,45,10,18,29,32,35,39,43,46,4,null,12,24,26,30,null,null,null,null,38,null,42,44,null,48,3,9,null,14,22,null,null,27,null,null,37,null,41,null,null,null,47,49,null,null,5,null,13,15,21,23,null,28,null,null,null,null,null,null,null,null,null,8,null,null,null,17,19,null,null,null,null,null,7,null,16,null,null,20,6]

    and the expected one is:

    [2,0,34,null,1,25,40,null,null,11,31,35,45,10,18,29,32,null,36,43,46,4,null,12,24,26,30,null,null,null,39,42,44,null,48,3,9,null,14,22,null,null,27,null,null,38,null,41,null,null,null,47,49,null,null,5,null,13,15,21,23,null,28,37,null,null,null,null,null,null,null,null,8,null,null,null,17,19,null,null,null,null,null,null,null,7,null,16,null,null,20,6]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.