Тёмный

Check if Binary Tree is Binary Search Tree 

Tushar Roy - Coding Made Simple
Подписаться 245 тыс.
Просмотров 122 тыс.
50% 1

Given a binary tree, return true if it is binary search tree else return false.
github.com/mis...
github.com/mis...

Опубликовано:

 

21 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 152   
@BrianFaure1
@BrianFaure1 6 лет назад
If anyone would like to see a simple Python implementation, check out my recent lesson: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-azupT01iC78.html
@CindyAlexius
@CindyAlexius 7 лет назад
Wow, you're walk-throughs are the best I've found on ds & as. Thanks! keep up the excellent work.
@meganlee5897
@meganlee5897 7 лет назад
note:this algorithm assumes 1)there could be duplicate 2)left subtree
@czerox16
@czerox16 3 года назад
in a binary search tree there would never be duplicate, wouldn't be?
@saurabhgupta1595
@saurabhgupta1595 3 года назад
@@czerox16 NO
@jamiecrowley7095
@jamiecrowley7095 7 лет назад
Wow, this has helped a lot. The columns you made to step through the recursive calls was a great idea, I'm usually writing stuff all over the place & it just winds up messy & confusing.
@pha1994
@pha1994 5 лет назад
Just do an inorder traversal and keep updating two consecutive values. the moment they are out of order is when you declare False.
@piyushmajgawali1611
@piyushmajgawali1611 5 лет назад
Fine but what if you want Left to contain less than or EQUAL to as well 1 / 1 is OK but not 1 \ 1
@aj9706
@aj9706 5 лет назад
But in interviews they will ask you different approach not the inorder one.
@aj9706
@aj9706 5 лет назад
@@piyushmajgawali1611 but BST is, on the left it is root.
@anurp4173
@anurp4173 4 года назад
exactly, I did not understand why a simple in order traversal will not do here. It is such a simple way to do it. I also get that in the interviews they do not like the in-order approach and that beats me.
@Houseready01
@Houseready01 4 года назад
that will not handle duplicates well
@tusov8899
@tusov8899 3 года назад
The recursion diagram of running test cases is really really helpful to fix bug, THANK YOU Tushar !
@anirudhsarma4233
@anirudhsarma4233 6 лет назад
I might be late to this thread. But there seems to be an inorder traversal based solution. Would you cover that as well?
@chittytherobot
@chittytherobot 8 лет назад
Hey Tushar - guess I bumped into a few edge cases ; in the code - why would we do only root.data
@KoushikChowdhury2016
@KoushikChowdhury2016 4 года назад
Your code doesn't work in cases where the input is [2147483647] or [-2147483648 ,null, 2147483647]
@vishalrana4093
@vishalrana4093 6 лет назад
Why not to perform inorder traversal of the tree and check simultaneously whether the data is in sorted order or not? If yes,then the tress is BST else not
@harmeetbindra6978
@harmeetbindra6978 6 лет назад
That's one way to do it but it will be slower than this method.
@juggernaut420
@juggernaut420 6 лет назад
That'd be O(n) space, this is O(1) space.
@tomross2124
@tomross2124 6 лет назад
It can be done in constant space too. Instead of storing all elements, store last element in In-order traversal in a single variable and check every node value to that variable. After every comparison update the variable value to node value. O(1) Space .:-) Java Code : public int min = Integer.MIN_VALUE; // This will be a global variable like min, max referred in the video public boolean isBST(TreeNode root, int min){ if(root == null) return true; boolean left = isBST(root.left,min); if(min >= root.val) return false; min = root.val; boolean right = isBST(root.right,min); return(left && right); }
@tomross2124
@tomross2124 6 лет назад
I don't think it will be slow. Check the below code. Same complexity (time and space); Java Code : public int min = Integer.MIN_VALUE; // This will be a global variable like min, max referred in the video public boolean isBST(TreeNode root, int min){ if(root == null) return true; boolean left = isBST(root.left,min); if(min >= root.val) return false; min = root.val; boolean right = isBST(root.right,min); return(left && right); }
@EngMohmdNoor
@EngMohmdNoor 6 лет назад
Inorder traversal will do the job in a simpler way. Both are O(n) space since recursion (stack) is used.
@akhilguptavibrantjava
@akhilguptavibrantjava 5 лет назад
In recursive call, the value passed as min and max should be return isBST(root.left,root.data-1,min) && isBST(root.right,max,root.data+1);
@anikkhan8811
@anikkhan8811 3 года назад
The table helps a lot to track the recursive calls. Thanks Sir :)
@khaledacmilan
@khaledacmilan 6 лет назад
Thank you very much, Tushar!. I had a thought on this, can't we just go InOrderTraversal keep adding to a list/array for instance and then check if the list/array is sorted?.
@kevinsheeran2579
@kevinsheeran2579 6 лет назад
Yes but it is not space optimal. This is using O(n) storage.
@PradeepSingh-ov3bt
@PradeepSingh-ov3bt 6 лет назад
we can iterate through the tree only and check the prev node is smaller than the present node no need for an extra space buddies
@EngMohmdNoor
@EngMohmdNoor 6 лет назад
Both are O(n) space since recursion (stack) is used
@Cube2deth
@Cube2deth 4 года назад
@@EngMohmdNoor We can use an iterative in order traversal, and get O(1) space
@zshanz
@zshanz 8 лет назад
Thanks for the solution.. whats the space complexity of this ? would it be O(height of tree) since we are using those many nodes on stack for recursion
@Bakepichai
@Bakepichai 7 лет назад
Simplicity is the ultimate sophistication.... Simple :)
@madhukiranattivilli2321
@madhukiranattivilli2321 3 года назад
there is an even simpler algo. perform inorder traversal. if at any stage the current node value is smaller than previous node value it is not BST
@shawnmofid7131
@shawnmofid7131 4 года назад
I was struggling with an annoying problem, and your video helped a lot. Thank you so much.
@krishnajha1
@krishnajha1 3 года назад
Best explanation for this question on RU-vid
@crisag.2698
@crisag.2698 5 лет назад
I understand that the worst-case runtime of this algorithm is O(N), however, is it true to say that in the case of it NOT being a binary search tree, the runtime would be O(N/2), since once one of the subtrees returns false, there's no need to check the other half of the tree, since FALSE && TRUE is already determined to be false?
@vivekmit
@vivekmit 4 года назад
This binary tree traversing is PreOrder OR Inorder. Can we implement same logic with different traversing (InOrder/PostOrder) ,if yes ,will it be impact on algo complexity ?
@anandkulkarni2111
@anandkulkarni2111 6 лет назад
In order traversal plus boost.circular but ffer.of size.2 gives most efficient solution O(n) time complexity and O(1) space complexity
@YogeshDarji99
@YogeshDarji99 7 лет назад
Just one suggestion at 0.17 , left is less than or equal to root(not just less) and right is greater than root. Btw nice video. Look forward to see more such videos. Good going Tushar!
@svdfxd
@svdfxd 5 лет назад
hi Tushar, As usual awesome explanation. However as some of the people have commented, even I was thinking why this cannot be achieved via In-Order Traversal? It will also take O(n) time and we can manage to compare the values using constant space. Can you please explain if this method is still efficient than In-Order traversal?
@ahrazmalik5807
@ahrazmalik5807 3 года назад
The best video on the internet on this problem
@czerox16
@czerox16 3 года назад
shouldn't the time expense be O(h) where h is the height of the tree?
@nehachaudhary3642
@nehachaudhary3642 6 лет назад
You explained this really well! I had a hard time finding a solution that was easy to understand! Thank you!
@muyuanchen3859
@muyuanchen3859 Год назад
best video to explain the BST.
@sparrownature9189
@sparrownature9189 5 лет назад
Hi thanks for making smaller videos. Keep making small length videos around ten minutes. And thank you for making videos.
@madhukiranattivilli2321
@madhukiranattivilli2321 3 года назад
during inorder traversal if current node data is lesser than previous data it is not a BST
@wowfan007
@wowfan007 6 лет назад
Loved the explanation, esp. table visualization
@crafter202
@crafter202 6 лет назад
we can do a inorder Traversal and store root.value in a List , If the List is sorted in Increasing order , it is a BST . (Simpler solution, but probably higher Space complexity)
@tomross2124
@tomross2124 6 лет назад
Instead of list just keep track of last element visited and compare next element with that. Same complexity
@tinyEnglish
@tinyEnglish 5 лет назад
The base thinking is ok. But there are some bugs in your solution. First there no anything condition need for root.val, is don't need be larger than Integer.MIN_VALUE, it can be Integer.MIN_VALUE. And it can be Integer.MAX_VALUE. You introduce an unnecessary condition into this problem. The right solution is to use null to avoid unnecessary condition. Like this: public boolean isValidBST(TreeNode root) { return isBST(root,null,null); } private boolean isBST(TreeNode node,Integer min,Integer max) { if (node==null) return true; if(min!=null && node.val=max) return false; return isBST(node.left,min,node.val) && isBST(node.right,node.val,max); }
@MohammadEhsanAnsari
@MohammadEhsanAnsari 3 года назад
Best video on internet sir
@m.a.hafeezqureshi4355
@m.a.hafeezqureshi4355 9 лет назад
Good Work Tushar. Thanks for this simple yet elegant explanation.
@sonalathawale426
@sonalathawale426 6 лет назад
Very clear step by step explanation! Hope to see more videos from you
@AzatDzhanybekov
@AzatDzhanybekov 8 лет назад
Good Job Tushar!
@Simply_maniyaa
@Simply_maniyaa 8 лет назад
Nice video. Really good explanation. if you can try explaining about time complexity as well,then it would be great.
@alicebobson2868
@alicebobson2868 4 года назад
very good explanation, the best so far
@pardeepsharma6502
@pardeepsharma6502 7 лет назад
Thanks, Sir g !! You have clarified recursion stack as well :)
@ankitagarwal4914
@ankitagarwal4914 4 года назад
Thanks for sharing !!..After watching 3 videos finally I land on this great one...
@lukeguan1397
@lukeguan1397 4 года назад
That's the greatest explanation in youtube
@snlagr
@snlagr 4 года назад
welcome back to th garage
@m.a.hafeezqureshi4355
@m.a.hafeezqureshi4355 9 лет назад
Hello Tushar, I have tried the code of isBT from your git repo and it doesnot seems to be working If available online, please reply
@m.a.hafeezqureshi4355
@m.a.hafeezqureshi4355 9 лет назад
+Tushar Roy : The code written in java for isBST, it throws some error
@rsjsdqps7363
@rsjsdqps7363 7 лет назад
Fantastic! So simple and elegant!
@WowPlusWow
@WowPlusWow 4 года назад
What is the space complexity?
@kokonodray9859
@kokonodray9859 3 года назад
can i just do an inorder traversal and find out if the traversal is sorted or not as inorder traversal of a binary tree is always sorted.
@e889.
@e889. 5 лет назад
Well done Gautam Gambhir
@amitpandit3018
@amitpandit3018 4 года назад
Can we some iterative approach to do it ?
@OverLordOfDa3rdWorld
@OverLordOfDa3rdWorld 3 года назад
incredibly explained! thank you!
@emersonmicu1683
@emersonmicu1683 8 лет назад
Will Inorder traversal work? I mean to keep that last element and to compare with next and so on. Inorder traversal will give us the elements in ascending order so we compare if( last
@simrandotdev
@simrandotdev 7 лет назад
It will works. Thats is also O(n) but this is one more efficient.
@tomross2124
@tomross2124 6 лет назад
How come this is more efficient? Please explain.
@jasminewang8954
@jasminewang8954 7 лет назад
What is the function "isBSTIterative" for?
@razorhxh7371
@razorhxh7371 4 года назад
Thanks Tushar! That was super helpful
@uulita2129
@uulita2129 6 лет назад
Awesome!! Like the way you go through the solution. Thank you so much!
@kartavyaabbet123
@kartavyaabbet123 2 года назад
Sir ji maza aha gya smj kar
@albinpaul3429
@albinpaul3429 7 лет назад
We can use inorder traversal and checking if current node is greater than global variable set global variable as current else return not bst
@ritikchail7330
@ritikchail7330 3 года назад
Awesome walkthrough
@yuzhouwang5651
@yuzhouwang5651 4 года назад
what if the the type of tree node is written in template, how to define infinity
@aj9706
@aj9706 5 лет назад
Very well explained.Thank you
@tilakraj9392
@tilakraj9392 7 лет назад
This was a very good explanation.
@reo4465
@reo4465 3 года назад
it's a shame that this guy doesn't make videos anymore.
@gauravpendhari1995
@gauravpendhari1995 5 лет назад
Would you please comment your code on Github? It will be helpful for all the starters. Thanks!
@AkshaySarraf1993
@AkshaySarraf1993 6 лет назад
Can't assign infinity to a number. How would you actually execute it ?
@abhishekbhandari6362
@abhishekbhandari6362 6 лет назад
in C++, we have INT_MAX and INT_MIN inbuilt.
@armandomacedo6712
@armandomacedo6712 5 лет назад
this is PreOrder traversal right?
@kabitabhandari2183
@kabitabhandari2183 6 лет назад
Thanks for the code! Good explanation.
@hanscantanhede
@hanscantanhede 5 лет назад
very well explained! Thank you.
@hitec1691
@hitec1691 5 лет назад
This algo doesn't work on all test cases :( tried it on leetcode. for example when a tree has only one node and its value is equal to Integer.MAX_VALUE.
@sanchitkhare7977
@sanchitkhare7977 4 года назад
Just put the min and max to Long.MIN and Long.MAX, it will work on leetcode
@DAaaMan64
@DAaaMan64 6 лет назад
@3:33 WELCOME BACK to the GARAGE
@s_cube8543
@s_cube8543 4 года назад
1Kth like :D. Thanks for this series btw.
@nikhilmkul
@nikhilmkul 5 лет назад
What about the case where the tree is [1,null,1] i.e. root node is 1 and right child is 1. According to this logic, output is True
@baurks
@baurks 5 лет назад
I have the same question. Were you able to make any modifications and get it to work?
@priyankamalviya3613
@priyankamalviya3613 5 лет назад
Thanks Tushar! I always refer to your explanations when stuck, but this code doesnt work for (1,1,null) :(
@madhukalapala9673
@madhukalapala9673 5 лет назад
Great video... clear explanations... Thanks a lot
@alejandraz6080
@alejandraz6080 7 лет назад
genial, gracias desde bsas, Argentina :)
@nurture_your_hobby
@nurture_your_hobby 8 лет назад
Awesome Explanation. Thanks Bro :-)
@varunvikramsingh
@varunvikramsingh 7 лет назад
You have read it wrong Tushar, the condition if(root.datamax) it's an OR condition, you are saying it as AND condition while speaking, which may confuse some people initially.
@falakk22
@falakk22 7 лет назад
Big Thank you for cool execution flow illustration . I've best understood with your illustration but not agree with your example and code . PS :: Do Share your view point to below query . Query : Property says : " The left subtree of a node contains only nodes with keys less than the node’s key and Each node (item in the tree) has a distinct key. " Your example have 10 in left subtree same as value of root (10), What if we take 10 again instead of -5 , as per your flow in code it will pass and we will have duplicate values in BST . (Because 10 is again not large than max(10) but equal to 10 as per explained by you in second iteration .) I agree with GKG that to tighten up boundaries we can use following conditions : /* false if this node violates the min/max constraints */ if (node.data < min || node.data > max) return false; /* otherwise check the subtrees recursively tightening the min/max constraints */ return (isBSTUtil(node.left, min, node.data-1) && isBSTUtil(node.right, node.data+1, max)); // Allow only distinct values Ref : www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/
@UwUDibboChowdhury
@UwUDibboChowdhury Год назад
yeah I agree, I was also confused, as the code in video suggests there might be duplicates in BST. BTW it has been 5 years tho.
@rroy2812
@rroy2812 3 года назад
excellent explanation
@susmithakolli1525
@susmithakolli1525 5 лет назад
root.data >= max . I guess you missed the equal-to symbol there.
@ArpitDhamija
@ArpitDhamija 4 года назад
he was in Amazon , seatle
@liferoks26
@liferoks26 5 лет назад
Well explained bro, Thank you
@arshamazami159
@arshamazami159 3 года назад
great explanation thanks 👌
@johndoe-eh2ol
@johndoe-eh2ol 7 лет назад
So you are using recursion to solve this problem, and recursion uses call stack! One caveat - this could lead to stack overflow if the tree is ridiculously large.
@johndoe-eh2ol
@johndoe-eh2ol 7 лет назад
Thank you for this wonderful lesson btw :)
@bodlaranjithkumar
@bodlaranjithkumar 7 лет назад
You are right, John. Recursive approach is vulnerable to stack overflow error. We could use Depth-First or Breadth-First Traversal of the tree which have the same Time cost with same worst case Space Complexity. But, DF is more efficient with O(lgn) or O(d) {d : depth(Tree)} space complexity in best case/average case.
@ogbillity
@ogbillity 4 года назад
you made look simple. thank you.
@paulmlyniec37
@paulmlyniec37 5 лет назад
Nice one. Really appreciate it.
@raj_kundalia
@raj_kundalia 3 года назад
Thanks for the video.
@saicharan8675
@saicharan8675 5 лет назад
thank you sooo much, i have been banging my head and yo cleared it off.. thank you.. very good explination with good chart on the right side
@jackandjac
@jackandjac 8 лет назад
Hi Tushar, will this work on a BST like [Integer.MIN_VALUE,null,5,null,null,null,8]?
@NachiketJoshiTheBloodMage
@NachiketJoshiTheBloodMage 6 лет назад
no, it will not work, in this case, you have to use integer object instead of MAX nad MIN and the fact that they are default null.
@kangpeng9061
@kangpeng9061 2 года назад
so clearly,thank you
@TheGamerGuy201
@TheGamerGuy201 7 лет назад
Just a suggestion-It would be better if you also show us the working of the algorithm when the example DOESN'T satisfy the condition asked in the question.I mean for this question,it would've been better if you also showed how this algorithm worked for a binary tree which is NOT as bst.
@codestorywithMIK
@codestorywithMIK 7 лет назад
Thanks for the video
@bismeetsingh352
@bismeetsingh352 4 года назад
Should [1,1] be a valid BST. Leetcode says otherwise.
@prathashukla6596
@prathashukla6596 4 года назад
This is not working on [1,1]
@AmitSingh-ut4wt
@AmitSingh-ut4wt 4 года назад
nice explanation
@derpina615
@derpina615 2 года назад
Bruh. MIN & MAX won't work if root.val = Integer.MAX_VALUE :(
@ridimamittal4064
@ridimamittal4064 4 года назад
Thank you sir , God bless: )
@jamelhiq
@jamelhiq 4 года назад
I'm naming my son, Tushar
@reefat0904
@reefat0904 6 лет назад
Thanks. it was helpful!
@alexhong794
@alexhong794 5 лет назад
can you please try iteration ? Thank you
@aj9706
@aj9706 5 лет назад
Iteration is quite hard compared to recursive especially in tree's.
@SivaRamaPrasadMupparaju
@SivaRamaPrasadMupparaju 5 лет назад
This logic will fail for [2147483647,2147483647] ... Isn't it ? OR Algo here assumes duplicates Ok ??
@kajalmondal9745
@kajalmondal9745 3 года назад
Just amazing
@rtrs5413
@rtrs5413 4 года назад
YOU are the best
@prashant3430
@prashant3430 5 лет назад
This solution will fail for tree like {1,1}
Далее
Level Order Traversal of Binary Tree
7:57
Просмотров 67 тыс.
Morris Inorder Tree Traversal
11:44
Просмотров 146 тыс.
Check if a tree is bst or not
7:15
Просмотров 35 тыс.
Iterative Postorder Traversal of Binary Tree
8:29
Просмотров 79 тыс.
Binary Tree - 71: Check if given Binary Tree is BST
16:58
Binary Trees - Data Structures Explained
10:18
Просмотров 132 тыс.
Same Binary Tree
5:02
Просмотров 45 тыс.