Validate Binary Search Tree - Depth First Search - Leetcode 98

  Рет қаралды 234,783

NeetCode

NeetCode

Күн бұрын

Пікірлер
@NeetCode
@NeetCode 3 жыл бұрын
Tree Question Playlist: kzbin.info/www/bejne/hZ-2n2WOerZng7s
@dishaagarwal1530
@dishaagarwal1530 5 ай бұрын
Hi, just wanted to know that since condition is not for equal, wont test case with 2 nodes with same value fail say for this tree 23, left child is equal to root val not greater but this is not bst but running above code should not work on this case, let me know how this works
@rashaameen611
@rashaameen611 9 ай бұрын
great solution, if anyone is looking for Time and space complexity: Time: O(N) Space: O(N) This is because the DFS function is recursively called for each node in the BST, potentially leading to a call stack depth proportional to the number of nodes
@talalnajam8692
@talalnajam8692 2 жыл бұрын
great solution! My first intuition was to do an inorder traversal, and then do a one-pass to see if it's sorted. O(n). Downside is you have to loop through the entire tree even if the invalid node is the root's left child. class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: res = [] self.inorder_traversal(root, res) return self.is_sorted(res) def inorder_traversal(self, root, res): if root: self.inorder_traversal(root.left, res) res.append(root.val) self.inorder_traversal(root.right, res) def is_sorted(self, arr): if not arr: return False for i in range(1, len(arr)): if arr[i]
@joeltrunick9487
@joeltrunick9487 2 жыл бұрын
Actually, I think this is a cleaner solution, as long as you use lazy evaluation. In Clojure, I think this is the way to go. (defn inorder [tree] (if (= nil tree) [] (concat (inorder (second tree)) (list (first tree)) (inorder (nth tree 2 nil))))) (apply
@gamerversez5372
@gamerversez5372 2 жыл бұрын
I had solved this question on leetcode in this way it went pretty well and when I tried on gfg , i got a wrong answer at a test case 🥲
@VasheshJ
@VasheshJ 2 жыл бұрын
I think this approach is fine. If you keep on checking if the number appended to the stack (while doing an inorder traversal) is lesser than or equal to the number just before it, then you can return False. It also reduces space complexity bcoz u only need to store one number in the stack. Check out my solution: class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: result = [] stack = [] while True: while root: stack.append(root) root = root.left if not stack: break node = stack.pop() if result: if result[0] >= node.val: return False result.pop() result.append(node.val) root = node.right return True
@anwarmohammad5795
@anwarmohammad5795 2 жыл бұрын
this was a good one too..
@mehershrishtinigam5449
@mehershrishtinigam5449 2 жыл бұрын
arey wah so smart bro. O(n) ez soln. very good
@aditisharma2448
@aditisharma2448 3 жыл бұрын
Looking at the the approach and the way you have explained it made my day. Absolutely beautiful and effortless.
@NeetCode
@NeetCode 3 жыл бұрын
Thanks, I'm happy it was helpful :)
@SritamNanda-x5h
@SritamNanda-x5h 7 ай бұрын
@@NeetCode hey how do u do it in c++,my problem is what should i replace inplace of inifinity??
@tharunkumar5095
@tharunkumar5095 4 ай бұрын
​​​@@SritamNanda-x5h If u still haven't figured it out Use long int For example, long left = LONG_INT
@sachinprabhuk6241
@sachinprabhuk6241 2 ай бұрын
@@SritamNanda-x5h Long datatype should do the trick.
@jackarnold571
@jackarnold571 4 жыл бұрын
Dude, thank you so much for these videos! I struggled with understanding this (and many other) problem, even after looking at solutions in the discuss section. After watching this it makes perfect sense!
@NeetCode
@NeetCode 4 жыл бұрын
Thanks! I'm happy it was helpful
@julesrules1
@julesrules1 2 жыл бұрын
Everything in this video is perfect. The logic, the way you explained it, the code, even the font! This made my day. Thanks!
@around_the_kyushu_2000
@around_the_kyushu_2000 2 жыл бұрын
These solutions are so efficient and elegant, thank you so much. I feel like I could never get to these solutions on my own.
@sugandhm2666
@sugandhm2666 2 жыл бұрын
In java u need to pass left = Long.MIN_VALUE and right = Long.MAX_VALUE because there are test cases in which root value itself is Integer.MAX_VALUE and the if condition doesnt hit to return false. So having long as left and right boundaries make sure that node values(int type) lie within given range. Because longMIN < Integer < LongMax is always true class Solution { public boolean isValidBST(TreeNode root) { return helper(root, Long.MIN_VALUE, Long.MAX_VALUE); } private boolean helper(TreeNode node, long left, long right) { if(node==null) return true; if(!(node.valleft)) return false; return (helper(node.left, left, node.val) && helper(node.right, node.val, right)); } }
@reemmikulsky1382
@reemmikulsky1382 Жыл бұрын
this bug is also relevant in cpp
@selfhelpguy5589
@selfhelpguy5589 7 ай бұрын
Thank you so much!
@draugno7
@draugno7 Ай бұрын
they should've not given that test case...
@moobs
@moobs 7 күн бұрын
Alternatively can use a conditional check if it has been set ie using Integer = null or another boolean
@2NormalHuman
@2NormalHuman 5 күн бұрын
it's kind of unfair that the Python and JS devs won't run into this test case lol
@solodolo42
@solodolo42 Жыл бұрын
Nice one! for readability, I also re-wrote line 13 as[ if not (left < node.val< right): ] . Thanks
@dineshkumarkb1372
@dineshkumarkb1372 Жыл бұрын
Wonderful. You read my mind. The first intuitive solution that came to my mind was to blindly compare the node values on the left and right with its immediate root node. I think its not only important to teach how to build an intuition but also to teach how not to build one. Thanks a ton for doing that. That's what has made your channel stand out. Keep it up!
@ranjeetkumaryadav3978
@ranjeetkumaryadav3978 2 жыл бұрын
One other simple solution can be, do inorder traversal and compare current value with last visited value.
@jugsma6676
@jugsma6676 8 ай бұрын
exactly!
@PhanNghia-fk5rv
@PhanNghia-fk5rv 7 ай бұрын
nice one bro
@surajpatil7895
@surajpatil7895 7 ай бұрын
It will not work as he already shown the example for that. If root node right node is greater, that's good. But if root node right node's left node is smaller than root but greater than it's parent, then it will send true though answer is false
@minhvulai_yt
@minhvulai_yt 6 ай бұрын
@@surajpatil7895 it will work since inorder traversal read your tree from left to right, meaning, if we have a tree like in the video, the result of inorder traversal would be [3, 5, 4, 7, 8]. Since 4 is greater than the prev number, return False
@of_mc9182
@of_mc9182 5 ай бұрын
@surajpatil7895 You've misunderstood the example. What he showed was not an in-order traversal but simply checking the children of the current parent node.
@AwesomeCadecraft
@AwesomeCadecraft Жыл бұрын
I love how you present the problems so well, I figured it out at 3:23
@UsamaAziz-lb7ky
@UsamaAziz-lb7ky 4 ай бұрын
We can also do this by evaluating max and min value from a node. A node's value should always be greater than max value from all of its left nodes, and should be less than min value of all of its right nodes class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: return self.isValid(root) def isValid(self, root): if not root: return True if not (root.val > self.getMaxValue(root.left) and root.val < self.getMinValue(root.right)): return False return self.isValid(root.left) and self.isValid(root.right) def getMaxValue(self, node): if not node: return float("-inf") return max(node.val, self.getMaxValue(node.left), self.getMaxValue(node.right)) def getMinValue(self, node): if not node: return float("inf") return min(node.val, self.getMinValue(node.left), self.getMinValue(node.right))
@tomonkysinatree
@tomonkysinatree 5 ай бұрын
Drawing out the solution was really good for this problem. I did the anticipated thing you pointed out at the beginning... then I tried to account for the issue when I realized what was wrong but couldn't frame the problem right. I think I am starting to jump into the code too soon. I need to be better about trying to break down the problem into smaller pieces first
@niravarora9887
@niravarora9887 11 ай бұрын
My first intution was to follow inorder traversal and store it in the list, then validate if the list is sorted, I passed all the tests with it. Then I was trying to follow the approach you mentioned but figuring out left boundary and right boundary was actually very tricky, I am not sure if I could come up with that solution on my own.
@rahuldey1182
@rahuldey1182 2 жыл бұрын
This guy is the Mozart of Leetcode.
@edwardteach2
@edwardteach2 3 жыл бұрын
U a God # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isValidBST(self, root, low = float('-inf'), high = float('inf')): """ :type root: TreeNode :rtype: bool """ if not root: return True if not (low < root.val < high): return False left = self.isValidBST(root.left, low, root.val) right = self.isValidBST(root.right, root.val, high) return left and right
@NeetCode
@NeetCode 3 жыл бұрын
Thanks again 😄
@TheBeastDispenser
@TheBeastDispenser Жыл бұрын
Thanks for this! I feel into the simple trap you mentioned at the beginning and was confused why I was failing some test cases.
@rushikeshkulkarni1784
@rushikeshkulkarni1784 3 ай бұрын
I exactly came at the point when i understood the failure point with same examples , great explanation :)
@ahmedamr1124
@ahmedamr1124 2 ай бұрын
i used postorder and returned max and min for left and right node and if they are valid or not but your solution is much straight forward
@piyusharyaprakash4365
@piyusharyaprakash4365 Жыл бұрын
My solution was to find the inorder traversal using dfs, store it in an array then just check if that array is sorted or not. The overall time complexity is O(N) also! it was easier to understand
@justinvilleneuve251
@justinvilleneuve251 Жыл бұрын
same. You can just keep track of the last value visited in a variable "previous" instead of storing everything in an array. That way, you compare the current value with previous. If at any time current
@justinvilleneuve251
@justinvilleneuve251 Жыл бұрын
this way you use O(1) space
@hoixthegreat8359
@hoixthegreat8359 3 ай бұрын
​@@justinvilleneuve251 You still use O(N), due to your recursive stack. But, depending on how you write your code, it may run slightly faster if you return immediately on finding an issue.
@danielsun716
@danielsun716 2 жыл бұрын
One quick question, 7:47, why we cannot set the base case like this if left < node.val < right: return True ?
@skp6114
@skp6114 2 жыл бұрын
Just because the current node is true, it doesn't mean the children are true. We can't break out before calling the recursive function on the children. If false, we can break out since there is no point checking the children.
@danielsun716
@danielsun716 2 жыл бұрын
@@skp6114 Right!
@aayushgupta6914
@aayushgupta6914 2 жыл бұрын
Hey Neetcode, your algorithm takes O(n) time complexity and O(n) Space complexity (as you are traversing the tree recursively). Wouldn't it be much simpler if one were to take an inorder traversal and a single loop to check if the inorder traversal list is in acsending order or not. It would be of O(n) time and space complexity too.
@_nh_nguyen
@_nh_nguyen 2 жыл бұрын
Taking an inorder traversal and another loop actually takes 2n while NeetCode's algorithm takes n. Which means it is twice slower while both are O(n).
@test-y1p7r
@test-y1p7r 2 жыл бұрын
I was thinking exactly this. I think your way is more intuitive and easy to understand than what is shown in the video!
@jakjun4077
@jakjun4077 Жыл бұрын
@@_nh_nguyen can u explain why it is 2n for the solution since u only traverse all the node once why times two
@StfuSiriusly
@StfuSiriusly Жыл бұрын
@@_nh_nguyen constants mean nothing when talking about time complexity. 2n and n are equivilent unless you meant n^2
@piyusharyaprakash4365
@piyusharyaprakash4365 Жыл бұрын
@@_nh_nguyen 2n reduces down to n so it's not that much big of a deal
@wonheeAlgorithm
@wonheeAlgorithm 2 жыл бұрын
Wow, It's so much cleaner and understandable than leetcode solution. Thanks for the video. It helps a lot!!
@iamburntout
@iamburntout 11 ай бұрын
the way you write code is art
@tvrao123
@tvrao123 2 жыл бұрын
Very simple logic is complicated Max of left sub tree should be less than root and min of right sub tree should be greater than root
@ladydimitrescu1155
@ladydimitrescu1155 Жыл бұрын
coming back to this video after a month, best explanation out there!
@rajeshg3570
@rajeshg3570 2 жыл бұрын
I've been watching lot of solutions for this problem but i think this is the easiest and the best one.. simple superb.. thanks for this..
@blindview2006
@blindview2006 Жыл бұрын
You can do inorder traversal without appending to array, just compare with the previous val when you're printing, instead of adding to array. This is same time and space
@penguin1234ification
@penguin1234ification 3 жыл бұрын
Thank you ! this is what I needed to click and understand.
@johnnylch18
@johnnylch18 Күн бұрын
I'm a little confused about why the condition needs to be `not (node.val < right and node.val > left)` could it not be instead `(node.val > right and node.val < left)` ?
@roni_castro
@roni_castro Жыл бұрын
I'd change left/right to min/max, so it's easier to understand and reduce confusion, as left reminds left node and so do right.
@backflipinspace
@backflipinspace Жыл бұрын
Imo, the left and right range can be a bit confusing. Just do a simple inorder traversal, as a valid BST will always print a sorted series during inorder. So we just need to verify that and we're done.
@noelcovarrubias7490
@noelcovarrubias7490 Жыл бұрын
@@backflipinspace can you explain that a bit further? What do you mean by “in order”
@abyszero8620
@abyszero8620 Жыл бұрын
min/max would clash with standard library functions, so it's good practice not to name variables exactly the same.
@abyszero8620
@abyszero8620 Жыл бұрын
​@@noelcovarrubias7490"in-order" traversal is a specific variant of DFS on trees. For a valid BST, an in-order DFS traversal pattern is guaranteed to "visit" the nodes in globally increasing order.
@khoango9241
@khoango9241 Жыл бұрын
@5:37 Why is the upper bound 7? Is it supposed to be infinity?
@adambarbour4203
@adambarbour4203 Жыл бұрын
usually don't comment on videos but this is amzing. Just summed up about a week of lectures in 10 minutes
@hickasso
@hickasso 2 жыл бұрын
Man, your channel is a divine beast. God, this is helping me so much, ty
@andrewpagan
@andrewpagan 2 жыл бұрын
I remember looking at this problem 2 years ago and just being stumped. You made it so easy to understand in less than 10 minutes. Thank you so much!
@deepakphadatare2949
@deepakphadatare2949 2 жыл бұрын
I wanna code like you .You make it sound so easy and simple.I really like your channel.If u ever in Newyork I wanna meet you.
@guynameddan427
@guynameddan427 3 жыл бұрын
Thanks for the explanation. Had one question. @6:45 you said the time complexity is O(2n). I get why that's just O(n) but why 2n to begin with?
@appcolab
@appcolab 2 жыл бұрын
O(2N) for the both trees left and right but we drop the constant 2N to O(N)
@timhehmann
@timhehmann 2 жыл бұрын
For each call of the function "valid" we have to make 2 comparisons (comparisons have O(1) time complexity) -> node.val < right -> node.val > left We touch each node only once (so we call the function "valid" N times in total), therefore it's O(2n) = O(n)
@hamoodhabibi7026
@hamoodhabibi7026 2 жыл бұрын
wow how do you come up with these solutions! leetcode master! mind blown every time
@aadityakiran_s
@aadityakiran_s Жыл бұрын
What if the root node or any other node inside is infinity or -infinity? Then this solution would break. If you put an equal's sign in addition to the comparators (=) then it will break if a tree is there with both left, right and its own value the same or if any value repeats in the BST. How did this solution pass that test case? Does it have something to do with it being written in Python?
@alexkim8965
@alexkim8965 Жыл бұрын
Same question here. Does infinity considered smaller/bigger than any legal float value? Edit: I just did quick google search, and it is considered smaller/bigger than any legal number when comparing in Python. For Java, use Double.NEGATIVE_INFINITY & Double.POSITIVE_INFINITY, instead of Integer.MIN_VALUE & Integer.MAX_VALUE. I just confirmed the difference in LeetCode.
@kevinsu9347
@kevinsu9347 3 жыл бұрын
I really like your explanation, thanks dude
@haoli8983
@haoli8983 5 ай бұрын
i found some solution on leetcode solutions. it's short. but hard to know what's going on. your solution is better than that to understand.
@jaymistry689
@jaymistry689 Жыл бұрын
I didn't really get your brute force but my brute force was to just create BST into sorted array by inorder traversal and check if the array is sorted or not. BUT AS ALWAYS YOUR SOLUTION WAS VERY CLEAVER
@piyusharyaprakash4365
@piyusharyaprakash4365 Жыл бұрын
That's not brute force I also came with the same solution using the inorder but the time complexity is O(N) but also taking O(N) space that's not brute force!
@shaked1233
@shaked1233 2 жыл бұрын
Im wondering why the "if not" and not regular if, any reason behind it?
@placementbaadshah8604
@placementbaadshah8604 2 жыл бұрын
kzbin.info/www/bejne/goO7pGCrg62Jj7M
@amritpatel6331
@amritpatel6331 2 жыл бұрын
You have explained so nicely. Thank you so much.
@icvetz
@icvetz 3 жыл бұрын
Hey NeetCode. May I ask what program you use for drawing your diagrams? Thanks!
@NeetCode
@NeetCode 3 жыл бұрын
Sure, I use Paint3D
@sarthakjain1824
@sarthakjain1824 Жыл бұрын
best explanation there can be for this question
@ax5344
@ax5344 3 жыл бұрын
@ 8:43 , valid(node.left, left, node.val), if node.left is our current node, for me this is checking whether current node is between float"-inf" and node.parent. So current node should be smaller than its local parent. But the challenge @4:45 is 4 is smaller than its local parent, it is just bigger than the node two levels above. I got lost there. Any advice? (I know the code is right, but I just don't understand why...)
@lajoskicsi6910
@lajoskicsi6910 2 жыл бұрын
Same for me, did you find anything out since then?
@prajjwaldubey5787
@prajjwaldubey5787 Жыл бұрын
i have solved this by taking the in order traversal of the BST ,and if the traversal is strictly increasing then it is a BST otherwise not
@Masterof_None
@Masterof_None Жыл бұрын
i made a function for inorder traversal then return an array and compared with an sorted version of array but this way seems much easier
@backflipinspace
@backflipinspace Жыл бұрын
you dont really need to print and compare the entire sorted array. just maintain a variable "lastSeen" during your inorder traversal and keep checking if lastSeen < root.val....if yes then update the lastSeen; if not return false.
@backflipinspace
@backflipinspace Жыл бұрын
This is a good solution but imo, a better and simpler way would be to just traverse the tree in "inorder". All BST's print out a sorted sequence when traversed in inorder. So all we really need to do is to check whether the last value we saw during our inorder traversal was smaller than my current node value; for which we can easily just maintain a global variable. That's it!! //Pseudocode: last = None def BST(Node root) { //base condition if(root == null){ return True } //left if(!BST(root.left)){ return False } //value comparision if(last == None){ last = root.val; }else{ if(last < root.val){ last = root.val }else{ return False } } //right if(!BST(root.right)){ return False } return True }
@StfuSiriusly
@StfuSiriusly Жыл бұрын
How is this simpler or better? The recursive solution is quite simple and elegant. Also you cant really say this is 'better' its just a different iterative way of solving it.
@jointcc2
@jointcc2 Жыл бұрын
​@@StfuSiriusly Well first of all, the iterative solution has the same time and space complexity as the recursive solution and if you happen to know anything about DFS inorder traversal you know it preserves order, so once you put all tree values in an array the rest is just checking whether the values in the array are in strictly increasing order. If you are in an interview this is the kind of solution that would come up to your mind instantly, which in a lot of times I think is better than coming up with a recursive case that may be error-prone. When I first tried this question I thought of both solutions, but I decided to go for the recursive solution and made the exact mistake Neetcode mentioned at the beginning of the video. This may be a good learning opportunity for myself but under interview condition it's always better to come up with solution having an easy and intuitive explanation while not compromising space and time complexity.
@arunraj2527
@arunraj2527 2 жыл бұрын
I was asked this question as a follow up for a BST question in Google and I bombed it :(. It was easy but at that moment of time this did not cross my mind.
@jugsma6676
@jugsma6676 8 ай бұрын
One simple method is to do inorder tree traversal: def isValidBST(self, root: Optional[TreeNode]) -> bool: res = [] def test(node, res): if not node: return True test(node.left, res) res.append(node.val) test(node.right, res) return res test(root, res) print(res) if len(res) != len(set(res)): return False return True if sorted(res) == list(res) else False
@jananisri6214
@jananisri6214 2 жыл бұрын
Can someone explain this line - valid(node.right, node.val, right). I don't understand how node.val comes in the place of left node.
@timhehmann
@timhehmann 2 жыл бұрын
I think the naming of the parameters is just a bit confusing here. left means left bound (or lower bound) and right means right bound (or upper bound). So left and right doesn't refer to nodes, but the bounds. If we go to the left subtree then "node.val" becomes the new upper/right bound. If we go to the right subtree then "node.val" becomes the new lower/left bound. class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: def valid(node, lowerBound, upperBound): if not node: return True if not (lowerBound < node.val and node.val < upperBound): return False; return valid(node.left, lowerBound, node.val) and valid(node.right, node.val, upperBound) return valid(root, float("-inf"), float("inf"))
@TheQuancy
@TheQuancy 2 жыл бұрын
Time complexity is O(n) Time | O(n) Space At that point, i'd rather just do the InorderTraversal, and check if the returned array is constantly increasing
@Jack-mc7qe
@Jack-mc7qe 2 жыл бұрын
avg space complexity will be more in that case since in best case also u would be maintaining o(n) space
@IK-xk7ex
@IK-xk7ex 2 жыл бұрын
Awesome, explanation is as simple as it
@dithrox
@dithrox 3 жыл бұрын
Thank you so much for these videos! Your solutions are crisp and easy to understand!
@NeetCode
@NeetCode 3 жыл бұрын
Thanks, glad they are helpful!
@pfiter6062
@pfiter6062 Жыл бұрын
I dont know why (root.val < left or root.val > right) gives me wrong answers
@bhaskyOld
@bhaskyOld 2 жыл бұрын
This solution may be tricky/difficult to implement in C++ ans there is no concept of +/- infinity. Also the range is given as INT_MIN to INT_MAX. Any comments?
@MagicMindAILabs
@MagicMindAILabs 2 жыл бұрын
// Recursive, In-Order validation // MIN/MAX not required TreeNode *prevv = NULL; bool helperIsValidBSTInorder(TreeNode *root, TreeNode *prevv) { if(root == NULL) { return true; } // In - Order business place where you do something // below conditions can be combined if(!helperIsValidBSTInorder(root->left, prevv*)) { return false; } if(prevv != NULL && root->val val) { return false; } prevv = root; return helperIsValidBSTInorder(root->right/*, prevv); }
@akankshasharma7498
@akankshasharma7498 2 жыл бұрын
should I try to come up with better solution if they are like, "Faster than 10%" ?
@Cruzylife
@Cruzylife 2 жыл бұрын
this is a sneaky question , passed 68 edge cases without considering the upper and lower bownd.
@mashab9129
@mashab9129 3 жыл бұрын
very clear explanation as always. thank you!
@parthshah1563
@parthshah1563 2 жыл бұрын
Great solution! I found the solution using INORDER traversal, but I'm not sure whether it is optimal or not. Can someone help me? def inorder(root, res): if not root: return inorder(root.left, res) res.append(root.val) inorder(root.right, res) res = [] inorder(root, res) for i in range(len(res)-1): if res[i] >= res[i+1]: return False return True
@hoixthegreat8359
@hoixthegreat8359 3 ай бұрын
O(n) space and O(n) time, so identical.
@silambarasan.ssethu9367
@silambarasan.ssethu9367 3 жыл бұрын
Great explaination.Thanks dude
@rahuldass452
@rahuldass452 2 жыл бұрын
Super helpful video! Question: based this BST definition, we assume every node has a unique value? I.e., if there are two nodes with equal values, then the tree is not a valid BST, correct? Something to clarify/disucss within an interview setting...
@shreyaskaup
@shreyaskaup 2 жыл бұрын
Yes 😊
@hickasso
@hickasso 2 жыл бұрын
Yes, if its equal we dont have a binary search, because we have to discard one side to make the search more efficienty. I think kkk
@symbol767
@symbol767 2 жыл бұрын
Thanks for your explanation!
@jvarunbharathi9013
@jvarunbharathi9013 Жыл бұрын
What is the Space complexity of the Soution O(log(n)) worst case? log(n) being height of the tree
@mariammeky3444
@mariammeky3444 Жыл бұрын
helped me a lot thank you
@theysay6696
@theysay6696 3 жыл бұрын
It makes so much sense now!
@VARUNSHARMA-shanks
@VARUNSHARMA-shanks 3 жыл бұрын
What is the problem with doing inorder traversal then check if it is sorted ?
@sujithkumar1997
@sujithkumar1997 2 жыл бұрын
extra memory for list and time to check if list is sorted
@alibaba888
@alibaba888 3 жыл бұрын
the explanation made my day...
@pekarna
@pekarna 2 жыл бұрын
Hi, I am lazy so I did it simply: Filled a list using in-order, and then just checked if it's sorted.
@MagicMindAILabs
@MagicMindAILabs 2 жыл бұрын
Why you have used preorder traversal approach??? Any specific reason?? Inorder traversal also we can do 😅😅😅 What about post order traversal??? I see everywhere people make video with preorder only and don’t tell the reason behind this..
@austinkellum9097
@austinkellum9097 2 жыл бұрын
I would like to know as well. I get why we would use DFS.
@kaci0236
@kaci0236 10 ай бұрын
I could spend one year looking at this problem and I would never come up with infinity condition. I wonder if this a matter of practice and at some point it gets in to your intuition or you just have to be smart
@ashleyspianoprogress1341
@ashleyspianoprogress1341 11 ай бұрын
I got this question in an interview.
@brianyehvg
@brianyehvg 3 жыл бұрын
isnt traversing the tree with inorder traversal and putting it in an array and then going through the array also technically O(n)
@NeetCode
@NeetCode 3 жыл бұрын
Actually yes, i didn't think of that, but that is also a good solution.
@brianyehvg
@brianyehvg 3 жыл бұрын
@@NeetCode i guess your solution is better anyways :) O(1) space vs O(n) space
@iambreddy
@iambreddy 2 жыл бұрын
@@brianyehvg Not really. You dont need to store the entire array. Just maintain the prev node and check if current node > prev.
@blitzspirit
@blitzspirit Жыл бұрын
Reminder: please add complexity analysis.
@abhicasm9237
@abhicasm9237 2 жыл бұрын
I have been practicing these questions for 2 months now but still I am not able to get the logic for most of the questions. Can someone from the comments help me?
@prashanthshetty8337
@prashanthshetty8337 3 жыл бұрын
Very neat! thank you so much for making these videos. This is helping me a lot.
@reda-cf9gy
@reda-cf9gy Ай бұрын
guys i don't understand why [120,70,140,50,100,130,160,20,55,75,110,119,135,150,200] is a not a valid binary tree ?
@VishnuVardhan-gr6op
@VishnuVardhan-gr6op 2 жыл бұрын
Please go through time and space complexity!
@3ombieautopilot
@3ombieautopilot 8 ай бұрын
Did it using generators and inorder traversal.
@moeheinaung235
@moeheinaung235 Жыл бұрын
what's the time and space complexity?
@javatutorials6747
@javatutorials6747 Жыл бұрын
Using inorder traversal can also a solution sir
@sachins6196
@sachins6196 2 жыл бұрын
Beautifully done
@hassanforever11
@hassanforever11 3 жыл бұрын
Really nice explanation you made it look easy where as its seams complication at other resources thanks man
@tongwang9464
@tongwang9464 2 жыл бұрын
beautiful solution
@AbhishekBajpaiHere
@AbhishekBajpaiHere 4 ай бұрын
why not just do in-order traversal and check if it is sorted ?
@herono-4292
@herono-4292 Жыл бұрын
I don't understand the difference between the brute force and the optimize brut force. In both case we iterate trough each node and made a comparison.
@sartipablo
@sartipablo Жыл бұрын
by brute force they usually mean the slower code and the optimized brut force is usually the faster code which it matters when you are dealing with very large data.
@BTECESaumyaPande
@BTECESaumyaPande 3 жыл бұрын
You are the best 👏👏
@IvanRadonjic-j9f
@IvanRadonjic-j9f 11 ай бұрын
My Solution, please let me know what you guys think: # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ treeValues = [] def DFS_inOrder(current_node): if current_node.left is not None: DFS_inOrder(current_node.left) treeValues.append(current_node.val) if current_node.right is not None: DFS_inOrder(current_node.right) DFS_inOrder(root) #loop to check if it is sorted prev = treeValues[0] for i in range(1, len(treeValues)): if prev >= treeValues[i]: return False prev = treeValues[i] return True
@ashikmahmud1404
@ashikmahmud1404 Жыл бұрын
what if root = INT_MAX doesn't it gives wa.
@Code4You1
@Code4You1 2 жыл бұрын
Very smart way
@hiscientia6536
@hiscientia6536 2 жыл бұрын
Hi, I am new to python and when I write the exact same code I am getting error for the def isValidBST line. Does anyone else get the error?
@ladydimitrescu1155
@ladydimitrescu1155 Жыл бұрын
post the entire code that you have written
@netraamrale3850
@netraamrale3850 Жыл бұрын
Superb...!!!
@ovaisahmedbinnajeeb1897
@ovaisahmedbinnajeeb1897 Жыл бұрын
A slightly better time solution. As soon as we reach the k value we break from the recursive loop: res=[] def dfs(node): if not node: return dfs(node.left) res.append(node.val) if len(res)==k: return dfs(node.right) dfs(root) return res[k-1]
@billcosta
@billcosta Жыл бұрын
you're genius
@h3ckphy246
@h3ckphy246 5 ай бұрын
I solved it this way: checked if max value on the left side is less than current node and the min value on the right side is greater than the current node. But your solution seems cleaner. def isValidBST(self, root: Optional[TreeNode]) -> bool: minVal, maxVal = self.__validateBST(root) return not math.isinf(minVal) and not math.isinf(maxVal) def __validateBST(self, root: Optional[TreeNode]) -> tuple[Union[int, float], Union[int, float]]: if root is None: return (math.inf, -math.inf) minLeft, maxLeft = self.__validateBST(root.left) if maxLeft >= root.val: return (-math.inf, math.inf) minRight, maxRight = self.__validateBST(root.right) if minRight
@thevagabond85yt
@thevagabond85yt Жыл бұрын
can u give stack solution?
@abdelmalek9004
@abdelmalek9004 2 жыл бұрын
why you have written all that return statement ? i haven't undrstood
@tvrao123
@tvrao123 2 жыл бұрын
Very simple logic is complicated
Kth Smallest Element in a BST - Leetcode 230 - Python
10:56
NeetCode
Рет қаралды 187 М.
Hilarious FAKE TONGUE Prank by WEDNESDAY😏🖤
0:39
La La Life Shorts
Рет қаралды 44 МЛН
"Идеальное" преступление
0:39
Кик Брейнс
Рет қаралды 1,4 МЛН
GIANT Gummy Worm #shorts
0:42
Mr DegrEE
Рет қаралды 152 МЛН
LRU Cache - Twitch Interview Question - Leetcode 146
17:49
NeetCode
Рет қаралды 312 М.
Clone Graph - Depth First Search - Leetcode 133
11:48
NeetCode
Рет қаралды 236 М.
Same Tree - Leetcode 100 - Python
7:52
NeetCode
Рет қаралды 134 М.
Word Search - Backtracking - Leetcode 79 - Python
10:18
NeetCode
Рет қаралды 346 М.
Binary Tree Level Order Traversal - BFS - Leetcode 102
9:36
NeetCode
Рет қаралды 198 М.
Binary Tree Maximum Path Sum - DFS - Leetcode 124 - Python
15:19
70 Leetcode problems in 5+ hours (every data structure) (full tutorial)
5:27:20
Climbing Stairs - Dynamic Programming - Leetcode 70 - Python
18:08