Delete Node in a BST - Leetcode 450 - Python

Sdílet
Vložit
  • čas přidán 14. 10. 2024

Komentáře • 58

  • @ericgithinji5140
    @ericgithinji5140 Před rokem +184

    RIP to whoever gets this question in an interview without having studied the approach before

    • @doc9448
      @doc9448 Před 5 měsíci +1

      It's a standard data structure (binary tree) method. If you've ever taken Data Structures and Algorithms then you've seen this exact thing. It's basically like not knowing for-while loops or a (a slightly lengthier) print statement, except for DSA. Not trying to be an elitist but hopefully if anyone is self taught and doesn't know DSA they can take the time to learn it so they don't get tripped up by what is practically a leetcode easy. Btw I recommend neetcode's DSA course which I'm currently taking. He's basically the GOAT for this in 2024 (and probably will remain so in 2025 and 2026 at least)

    • @abhilashpatel3036
      @abhilashpatel3036 Před 3 měsíci

      @@doc9448 not everyone is from CS background

    • @APudgyPanda96
      @APudgyPanda96 Před 2 měsíci

      @@doc9448 elitist

    • @PorkBoy69
      @PorkBoy69 Před 2 měsíci

      @@doc9448 I took a graduate level DSA course, no I did not see this exact thing lol.

    • @Dom-zy1qy
      @Dom-zy1qy Před měsícem +10

      ​@@doc9448What point are you trying to make? By watching this video, everyone here is already studying DSA. Sometimes the basic primitives we use to approach algorithms problems require a unique approach. Coming to this solution in a 30-45min interview, while trying to fulfill the criteria of the interview (voicing your thoughts, asking clarifying questions, making sense to the interviewer) is not a trivial thing to do.

  • @aadil4236
    @aadil4236 Před rokem +10

    That is the best Recursion I have ever seen so far!! Thank you NeedCode!!

  • @jessicachen5619
    @jessicachen5619 Před rokem +3

    I finally understand the solution after watching your video! You're amazing!

  • @VEDANSHSHARMA-o6k
    @VEDANSHSHARMA-o6k Před 2 měsíci +3

    Line 27 is so so clever
    root.right = self.deleteNode(root.right, root.val)

  • @StellasAdi18
    @StellasAdi18 Před rokem +7

    That was bit tricky. In step 2 was thinking to append deleted nodes left chain to deleted nodes right nodes leftmost node.

  • @NeetCodeIO
    @NeetCodeIO  Před rokem +5

    If you're looking for today's daily LC problem, you can find it here czcams.com/video/UbyhOgBN834/video.html

  • @Rajib317
    @Rajib317 Před 9 měsíci +1

    Here I thought I got this correct after all the example cases got passed and all I needed to solve was [0]; expected [] .
    if(prev != null && prev.next != null){
    prev.left = root.right;
    pref.left.left = root.left;
    }

  • @stith_pragya
    @stith_pragya Před 10 měsíci +1

    Thank You So Much for this wonderful video.........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @studyaccount794
    @studyaccount794 Před 2 měsíci

    I'm a bit confused. Technically don't you think we are not deleting it? We are swapping values and deleting a different node. Also, what if the data is huge in the nodes? It in itself can take additional time.
    Found these questions in leetcode comment section of similar approach answers.

  • @MP-ny3ep
    @MP-ny3ep Před rokem

    Great explanation as always. Thank you

  • @himanshisharma7116
    @himanshisharma7116 Před rokem +1

    Thank you sir for all your efforts😁

  • @alivepenmods
    @alivepenmods Před 10 měsíci +3

    I'd reject anyone that changes node values.
    Pointer from up the call stack could be maintaining reference to any node, satellite data could also be involved.
    CLRS has a brilliant explanation on how to delete a node in a BST.

  • @myspace9358
    @myspace9358 Před 2 měsíci

    so gooddddd thank you so much

  • @RakeshVarmaPenumetcha
    @RakeshVarmaPenumetcha Před 8 měsíci

    Hey hi myself rakesh,
    I have found a mistake in ur explanation at 8:17 time that u will replace 5 value in node 4 but u only search for min in right subtree if node 4 has both right and left, but here 4 does not have left so we return node 4 right instead of searching for min in right subtree

  • @GuntherJones
    @GuntherJones Před 6 měsíci

    Thank you

  • @andrewtitus6839
    @andrewtitus6839 Před 4 měsíci

    I didnt think this one was that bad, but i have been practicing trees a bunch

  • @jakjun4077
    @jakjun4077 Před rokem +1

    can u provides a tree example where time complexity is o(2h)?

  • @edwardteach2
    @edwardteach2 Před 3 měsíci

    U a BST God

  • @MazineSuliman
    @MazineSuliman Před rokem

    You need to account for an instance where the root is not actually equal to k, line 16 should check if k == root.val

    • @haakonharnes
      @haakonharnes Před 8 měsíci

      Doesn't he account for root != k with root.val > k and root.val < k? Which other possibilities are there?

  • @nithinsastrytellapuri291
    @nithinsastrytellapuri291 Před 10 měsíci

    why is the time complexity the height of tree i.e. O(log(n)) instead of O(n) ? what if the tree is skewed and we have to delete the left most or right most element? then in that case we have to traverse all the elements right ?

    • @michaelrosa385
      @michaelrosa385 Před 9 měsíci

      If it's skewed then its not a BST

    • @Danee2108
      @Danee2108 Před 8 měsíci +1

      ​@@michaelrosa385Couldn't it still be a BST? If it was always balanced it would be an AVL.

    • @haakonharnes
      @haakonharnes Před 8 měsíci

      The time complexity is O(h) where h is the height of the tree.
      For balanced BSTs, the height is logn, so the complexity in that case is O(logn). For scewed BSTs, the worst-case height is n, so the time complexity in that case is O(n).

  • @khaledkord8021
    @khaledkord8021 Před 4 měsíci

    What if the smallest value in the right side tree was smaller than the current left. for example the node 4 had a left side 1.
    50
    / \
    30 60
    / \ \
    2 40 70
    /
    1
    will be converted to this INVALID bst:
    50
    / \
    1 60
    / \ \
    2 40 70

    • @zhuoqunwei1112
      @zhuoqunwei1112 Před 4 měsíci +6

      That won't be a valid binary search tree case, 1 should be placed on the left child of 2 instead of 40

  • @shivamtripathi4469
    @shivamtripathi4469 Před rokem +7

    This code have issue, when we have to delete root node.

  • @abhishekupadhyay9962
    @abhishekupadhyay9962 Před 2 měsíci

    Could you please explain how to do it Iteratively?

    • @denysivanov3364
      @denysivanov3364 Před měsícem +1

      its doable. Just solve linked list node removal question. Than draw BST with height 1, 2, 3, 4 and take a look how is efficient to remove nodes with different values. You will be able to solve this after some practice. Its not about solution of this particular problem but to learn methods how to research problems in general. How to dig =)

  • @ahmedmansour5032
    @ahmedmansour5032 Před rokem

    Can someone explain the assignment part at 10:08?
    Are we storing the root.left and root.right variables in order to later check if the node we found has a left or right child (as seen in the else statement later below)?

    • @gani3813
      @gani3813 Před rokem +2

      If you mean root.left and root.right on lines 12-15, we are not storing variables here, we are calling deleteNode recursevely and assigning it's result to left or right node.
      We call deleteNode recursively and trying to find "key". From line 12 to line 15, we comparing key to current node value, if search key is bigger than val we go right, if search key is less then val we go left. Because in valid Binary Search Tree left node has a value less than or equal to its parent, the right one has a val greater or equal to parent node.
      From line 16 to line 20 we are checking for case when found key node that has 0 or 1 child.
      Starting from line 22 we know that "key" node has 2 child nodes.
      So from line 23 to 26 we are searching for "min value" on right side of found "key" node, and replace "key" with that "min value".
      Now we need to delete min-val. Because we copied it's value to "key" node. So at line 27 we call deleteNode recursively on right side of found "key" node and pass root.val (which is equal to min val) as "new search key". How it removes "min value"? At the end it reaches to base case where root is null (line 9) or it will reach case with 0 and 1 child (lines 17-20).

    • @IntheBellyofaWhale
      @IntheBellyofaWhale Před rokem +1

      @@gani3813 Thanks, great explanation

  • @jakjun4077
    @jakjun4077 Před rokem +1

    and could u solves
    memory leakage issue? the memory address of the left most found node still not delete yet.

    • @frostytf2
      @frostytf2 Před 7 měsíci +1

      Python garbage collector handles this as it falls out of scope in the call stack

  • @christrifinopoulos8639
    @christrifinopoulos8639 Před 10 měsíci +7

    this shouldn't be medium fr

    • @mk-19memelauncher65
      @mk-19memelauncher65 Před 9 měsíci

      Too easy or too hard?

    • @dailyclipmafia5041
      @dailyclipmafia5041 Před 9 měsíci

      @@mk-19memelauncher65 too easy

    • @abhishekupadhyay9962
      @abhishekupadhyay9962 Před 2 měsíci

      @@mk-19memelauncher65 not too hard, but if you try to solve it iteratively (to save those recursion overheads) then it becomes a bit hard

  • @2024comingforyou
    @2024comingforyou Před 9 měsíci

    can anyone explain me why we need to assign calls to root.right and root.left

    • @antony9058
      @antony9058 Před 2 měsíci

      We are using recursion. So after we remove a left child, we have to connect (point) it to the replaced value which can be None or some other element.
      In the example above, after deleting 3, we have to replace it with 4. So after putting 4 there, we have to connect the left of 5 to point to that 3. That's what is happening.
      You can do this on a paper by drawing yourself to understand it better 😬🫡

  • @rajasaraf6602
    @rajasaraf6602 Před 8 měsíci +1

    😵

  • @ashwanikumar415
    @ashwanikumar415 Před 3 měsíci

    java script solution with more comments:
    // T: O(log(n)), S: O(1) (not counting stack frames for recursion)
    // being n the amount of nodes in the tree
    // T: O(h), S: O(h) (counting h stack frames for recursion)
    // being h the height of the tree (max elements of the bst = n = 2^h)
    if (null === root) { return null; }
    if (root.val === key) {
    // to delete a leaf node (no children) we can just return null
    if (null === root.left && null === root.right) { return null; }
    // at this point we need to delete the current node. so, we need to return a different one
    // we need to pick either the left or the right node
    if (null !== root.left && null !== root.right) {
    // this a complicated edge case that we can't solve right away
    //
    // we could pick the root.left node, but what if (root.left.right !== null)? where
    // are we going to attach our root.right subtree without overwriting any existing
    // reference?
    //
    // also, we could pick the root.right node, but what if (root.right.left !== null) too?
    //
    // so, these are our two possible (and equivalent) options:
    // 1) pick our root.right node as the root node, and find the minimum node in
    // the right subtree that has no left pointer, and assign the root.left node to it.
    //
    // 2) pick our root.left node as the root node, and find the maximum node in
    // the left subtree that has no right pointer, and assign the root.right node to it.
    //
    // here's an example of deleting node with val=5 without breaking the BST choosing option (1)
    //
    // 5 8
    // / \ / \
    // 3* 8 7 9
    // / \ / \ ---> /
    // 2 4 7 9 6
    // / /
    // 6 3*
    // / \
    // 2 4
    //
    // we'll choose option (1) and we'll find the minimum number in the right subtree that
    // has no left pointer
    // that one is going to be the node that will link to the left subtree of the current
    // -soon to be deleted- node. by doing that we'll preserve the structure of the BST
    // (nodes to the left of a node should be smaller, and numbers to the
    // right should be greater).
    let curr = root.right;
    while (curr.left) { curr = curr.left; }
    curr.left = root.left;
    return root.right;
    }

    // if left/right is null, then we can safely pick the one that is not null without
    // breaking the BST
    if (null === root.left) { return root.right; }
    if (null === root.right) { return root.left; }
    }

    if (key < root.val) {
    // look for our target node in the left subtree
    root.left = deleteNode(root.left, key);
    } else {
    // look for our target node in the right subtree
    root.right = deleteNode(root.right, key);
    }
    return root;
    };

  • @alexanderp7521
    @alexanderp7521 Před měsícem +1

    there is no way i'm going to remember this code 💀

    • @denysivanov3364
      @denysivanov3364 Před měsícem

      you need to draw BST and look at edge cases. You can solve this stuff on your own after some practice. Begin from linked lists.

    • @alexanderp7521
      @alexanderp7521 Před měsícem

      @@denysivanov3364 thanks. i've already solved some issues using linked lists and bst, including some medium difficulty ones, but this one looks specifically terrifying
      i'll just keep practicing, i guess. hopefully i'll learn something after all

    • @denysivanov3364
      @denysivanov3364 Před měsícem +1

      @@alexanderp7521 I recommend reading a book how to solve it by George Polya. It will help to develop methods how to solve problems in general. Talking about this don't give up. Just draw BST with height 1, 2, 3, 4. Look at edge cases, draw how tree should change to maintain BST property, from where you need to move Node to keep tree nice etc. Just draw and take a look. I did it iterative. Do it little by little, don't give up. You will learn new things how to dig.

    • @denysivanov3364
      @denysivanov3364 Před měsícem

      @@alexanderp7521 Just draw BST of size 1, 2, 3, 4 and look what you need to do there. How to find node, with what it needs to be replaced etc. Look for edge cases. I did it iteratively its doable.

  • @huntx...8573
    @huntx...8573 Před 9 dny

    Why is this so hard😢

  • @krateskim4169
    @krateskim4169 Před rokem

    Thank You