Delete Node in a BST - Leetcode 450 - Python

  Рет қаралды 48,041

NeetCodeIO

NeetCodeIO

Күн бұрын

Пікірлер: 57
@ericgithinji5140
@ericgithinji5140 Жыл бұрын
RIP to whoever gets this question in an interview without having studied the approach before
@doc9448
@doc9448 7 ай бұрын
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 4 ай бұрын
@@doc9448 not everyone is from CS background
@APudgyPanda96
@APudgyPanda96 4 ай бұрын
@@doc9448 elitist
@PorkBoy69
@PorkBoy69 3 ай бұрын
@@doc9448 I took a graduate level DSA course, no I did not see this exact thing lol.
@Dom-zy1qy
@Dom-zy1qy 2 ай бұрын
​@@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 Жыл бұрын
That is the best Recursion I have ever seen so far!! Thank you NeedCode!!
@VEDANSHSHARMA-o6k
@VEDANSHSHARMA-o6k 4 ай бұрын
Line 27 is so so clever root.right = self.deleteNode(root.right, root.val)
@NeetCodeIO
@NeetCodeIO Жыл бұрын
If you're looking for today's daily LC problem, you can find it here kzbin.info/www/bejne/i5PcmYKdd7NraZY
@jessicachen5619
@jessicachen5619 Жыл бұрын
I finally understand the solution after watching your video! You're amazing!
@StellasAdi18
@StellasAdi18 Жыл бұрын
That was bit tricky. In step 2 was thinking to append deleted nodes left chain to deleted nodes right nodes leftmost node.
@АндрейКондрашов-ш9к
@АндрейКондрашов-ш9к 3 ай бұрын
It's another approach that works also perfectly. Just a little bit more work to do
@Rajib317
@Rajib317 11 ай бұрын
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 Жыл бұрын
Thank You So Much for this wonderful video.........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@alivepenmods
@alivepenmods 11 ай бұрын
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.
@dailyclipmafia5041
@dailyclipmafia5041 10 ай бұрын
lol, no one likes you
@MP-ny3ep
@MP-ny3ep Жыл бұрын
Great explanation as always. Thank you
@himanshisharma7116
@himanshisharma7116 Жыл бұрын
Thank you sir for all your efforts😁
@RakeshVarmaPenumetcha
@RakeshVarmaPenumetcha 9 ай бұрын
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
@andrewtitus6839
@andrewtitus6839 5 ай бұрын
I didnt think this one was that bad, but i have been practicing trees a bunch
@studyaccount794
@studyaccount794 3 ай бұрын
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.
@jakjun4077
@jakjun4077 Жыл бұрын
can u provides a tree example where time complexity is o(2h)?
@myspace9358
@myspace9358 3 ай бұрын
so gooddddd thank you so much
@edwardteach2
@edwardteach2 5 ай бұрын
U a BST God
@khaledkord8021
@khaledkord8021 6 ай бұрын
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 5 ай бұрын
That won't be a valid binary search tree case, 1 should be placed on the left child of 2 instead of 40
@abhishekupadhyay9962
@abhishekupadhyay9962 4 ай бұрын
Could you please explain how to do it Iteratively?
@denysivanov3364
@denysivanov3364 2 ай бұрын
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 =)
@krateskim4169
@krateskim4169 Жыл бұрын
Thank You
@MazineSuliman
@MazineSuliman Жыл бұрын
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 9 ай бұрын
Doesn't he account for root != k with root.val > k and root.val < k? Which other possibilities are there?
@nithinsastrytellapuri291
@nithinsastrytellapuri291 11 ай бұрын
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 10 ай бұрын
If it's skewed then its not a BST
@Danee2108
@Danee2108 10 ай бұрын
​@@michaelrosa385Couldn't it still be a BST? If it was always balanced it would be an AVL.
@haakonharnes
@haakonharnes 9 ай бұрын
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).
@2024comingforyou
@2024comingforyou 10 ай бұрын
can anyone explain me why we need to assign calls to root.right and root.left
@tonypaus13
@tonypaus13 3 ай бұрын
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 😬🫡
@shivamtripathi4469
@shivamtripathi4469 Жыл бұрын
This code have issue, when we have to delete root node.
@jakjun4077
@jakjun4077 Жыл бұрын
and could u solves memory leakage issue? the memory address of the left most found node still not delete yet.
@frostytf2
@frostytf2 8 ай бұрын
Python garbage collector handles this as it falls out of scope in the call stack
@ahmedmansour5032
@ahmedmansour5032 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@gani3813 Thanks, great explanation
@christrifinopoulos8639
@christrifinopoulos8639 11 ай бұрын
this shouldn't be medium fr
@mk-19memelauncher65
@mk-19memelauncher65 10 ай бұрын
Too easy or too hard?
@dailyclipmafia5041
@dailyclipmafia5041 10 ай бұрын
@@mk-19memelauncher65 too easy
@abhishekupadhyay9962
@abhishekupadhyay9962 4 ай бұрын
@@mk-19memelauncher65 not too hard, but if you try to solve it iteratively (to save those recursion overheads) then it becomes a bit hard
@ashwanikumar415
@ashwanikumar415 4 ай бұрын
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; };
@rajasaraf6602
@rajasaraf6602 10 ай бұрын
😵
@huntx...8573
@huntx...8573 Ай бұрын
Why is this so hard😢
@bag_of_pixels
@bag_of_pixels 2 ай бұрын
there is no way i'm going to remember this code 💀
@denysivanov3364
@denysivanov3364 2 ай бұрын
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.
@denysivanov3364
@denysivanov3364 2 ай бұрын
@@bag_of_pixels 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 2 ай бұрын
@@bag_of_pixels 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.
@GuntherJones
@GuntherJones 7 ай бұрын
Thank you
Delete a node from Binary Search Tree
18:27
mycodeschool
Рет қаралды 1,1 МЛН
Making an Algorithm Faster
30:08
NeetCodeIO
Рет қаралды 147 М.
I thought one thing and the truth is something else 😂
00:34
عائلة ابو رعد Abo Raad family
Рет қаралды 5 МЛН
Disrespect or Respect 💔❤️
00:27
Thiago Productions
Рет қаралды 43 МЛН
How Much Tape To Stop A Lamborghini?
00:15
MrBeast
Рет қаралды 210 МЛН
Молодой боец приземлил легенду!
01:02
МИНУС БАЛЛ
Рет қаралды 1,9 МЛН
How I Approach a New Leetcode Problem (live problem solving)
25:31
Delete Node in a BST | Leet code 450 | Theory explained + Python code
16:04
Kth Smallest Element in a BST - Leetcode 230 - Python
10:56
NeetCode
Рет қаралды 182 М.
L44. Delete a Node in Binary Search Tree | BST | C++ | Java
15:48
take U forward
Рет қаралды 210 М.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 687 М.
Dynamic Programming isn't too hard. You just don't know what it is.
22:31
DecodingIntuition
Рет қаралды 197 М.
I Solved 100 LeetCode Problems
13:11
Green Code
Рет қаралды 245 М.
Insert into a Binary Search Tree - Leetcode 701 - Python
9:48
NeetCodeIO
Рет қаралды 15 М.
I thought one thing and the truth is something else 😂
00:34
عائلة ابو رعد Abo Raad family
Рет қаралды 5 МЛН