Delete Node in a BST - Leetcode 450 - Python

  Рет қаралды 43,462

NeetCodeIO

NeetCodeIO

Күн бұрын

Пікірлер: 58
@ericgithinji5140
@ericgithinji5140 Жыл бұрын
RIP to whoever gets this question in an interview without having studied the approach before
@doc9448
@doc9448 5 ай бұрын
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 2 ай бұрын
@@doc9448 not everyone is from CS background
@APudgyPanda96
@APudgyPanda96 2 ай бұрын
@@doc9448 elitist
@PorkBoy69
@PorkBoy69 Ай бұрын
@@doc9448 I took a graduate level DSA course, no I did not see this exact thing lol.
@Dom-zy1qy
@Dom-zy1qy Ай бұрын
​@@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!!
@jessicachen5619
@jessicachen5619 Жыл бұрын
I finally understand the solution after watching your video! You're amazing!
@VEDANSHSHARMA-o6k
@VEDANSHSHARMA-o6k 2 ай бұрын
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
@stith_pragya
@stith_pragya 10 ай бұрын
Thank You So Much for this wonderful video.........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@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к 2 ай бұрын
It's another approach that works also perfectly. Just a little bit more work to do
@himanshisharma7116
@himanshisharma7116 Жыл бұрын
Thank you sir for all your efforts😁
@MP-ny3ep
@MP-ny3ep Жыл бұрын
Great explanation as always. Thank you
@Rajib317
@Rajib317 9 ай бұрын
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; }
@myspace9358
@myspace9358 2 ай бұрын
so gooddddd thank you so much
@GuntherJones
@GuntherJones 6 ай бұрын
Thank you
@studyaccount794
@studyaccount794 Ай бұрын
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.
@edwardteach2
@edwardteach2 3 ай бұрын
U a BST God
@RakeshVarmaPenumetcha
@RakeshVarmaPenumetcha 7 ай бұрын
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
@alivepenmods
@alivepenmods 10 ай бұрын
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 9 ай бұрын
lol, no one likes you
@jakjun4077
@jakjun4077 Жыл бұрын
can u provides a tree example where time complexity is o(2h)?
@khaledkord8021
@khaledkord8021 4 ай бұрын
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 4 ай бұрын
That won't be a valid binary search tree case, 1 should be placed on the left child of 2 instead of 40
@andrewtitus6839
@andrewtitus6839 4 ай бұрын
I didnt think this one was that bad, but i have been practicing trees a bunch
@shivamtripathi4469
@shivamtripathi4469 Жыл бұрын
This code have issue, when we have to delete root node.
@nithinsastrytellapuri291
@nithinsastrytellapuri291 10 ай бұрын
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 9 ай бұрын
If it's skewed then its not a BST
@Danee2108
@Danee2108 8 ай бұрын
​@@michaelrosa385Couldn't it still be a BST? If it was always balanced it would be an AVL.
@haakonharnes
@haakonharnes 8 ай бұрын
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).
@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 8 ай бұрын
Doesn't he account for root != k with root.val > k and root.val < k? Which other possibilities are there?
@abhishekupadhyay9962
@abhishekupadhyay9962 2 ай бұрын
Could you please explain how to do it Iteratively?
@denysivanov3364
@denysivanov3364 Ай бұрын
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 =)
@jakjun4077
@jakjun4077 Жыл бұрын
and could u solves memory leakage issue? the memory address of the left most found node still not delete yet.
@frostytf2
@frostytf2 6 ай бұрын
Python garbage collector handles this as it falls out of scope in the call stack
@christrifinopoulos8639
@christrifinopoulos8639 9 ай бұрын
this shouldn't be medium fr
@mk-19memelauncher65
@mk-19memelauncher65 9 ай бұрын
Too easy or too hard?
@dailyclipmafia5041
@dailyclipmafia5041 9 ай бұрын
@@mk-19memelauncher65 too easy
@abhishekupadhyay9962
@abhishekupadhyay9962 2 ай бұрын
@@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 8 ай бұрын
can anyone explain me why we need to assign calls to root.right and root.left
@antony9058
@antony9058 2 ай бұрын
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 😬🫡
@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
@ashwanikumar415
@ashwanikumar415 3 ай бұрын
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 8 ай бұрын
😵
@huntx...8573
@huntx...8573 4 күн бұрын
Why is this so hard😢
@alexanderp7521
@alexanderp7521 Ай бұрын
there is no way i'm going to remember this code 💀
@denysivanov3364
@denysivanov3364 Ай бұрын
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 Ай бұрын
@@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 Ай бұрын
@@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 Ай бұрын
@@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.
@krateskim4169
@krateskim4169 Жыл бұрын
Thank You
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
12:34
NeetCodeIO
Рет қаралды 23 М.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 579 М.
This mother's baby is too unreliable.
00:13
FUNNY XIAOTING 666
Рет қаралды 30 МЛН
Стойкость Фёдора поразила всех!
00:58
МИНУС БАЛЛ
Рет қаралды 6 МЛН
Delete a node from Binary Search Tree
18:27
mycodeschool
Рет қаралды 1,1 МЛН
Kth Smallest Element in a BST - Leetcode 230 - Python
10:56
NeetCode
Рет қаралды 172 М.
Microservices are Technical Debt
31:59
NeetCodeIO
Рет қаралды 461 М.
L44. Delete a Node in Binary Search Tree | BST | C++ | Java
15:48
take U forward
Рет қаралды 197 М.
Is Computer Science still worth it?
20:08
NeetCodeIO
Рет қаралды 378 М.
Leetcode - Delete Node in a BST (Python)
8:30
Timothy H Chang
Рет қаралды 14 М.
Binary Search Tree Removal
14:10
WilliamFiset
Рет қаралды 45 М.
How I Approach a New Leetcode Problem (live problem solving)
25:31
5 Useful F-String Tricks In Python
10:02
Indently
Рет қаралды 313 М.