Check if Binary Tree is Binary Search Tree

แชร์
ฝัง
  • เผยแพร่เมื่อ 1 ก.พ. 2025

ความคิดเห็น • 152

  • @CindyAlexius
    @CindyAlexius 7 ปีที่แล้ว +56

    Wow, you're walk-throughs are the best I've found on ds & as. Thanks! keep up the excellent work.

  • @jamiecrowley7095
    @jamiecrowley7095 7 ปีที่แล้ว +1

    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.

  • @tusov8899
    @tusov8899 3 ปีที่แล้ว

    The recursion diagram of running test cases is really really helpful to fix bug, THANK YOU Tushar !

  • @shawnmofid7131
    @shawnmofid7131 4 ปีที่แล้ว

    I was struggling with an annoying problem, and your video helped a lot. Thank you so much.

  • @pha1994
    @pha1994 6 ปีที่แล้ว +19

    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 ปีที่แล้ว +1

      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 ปีที่แล้ว +1

      But in interviews they will ask you different approach not the inorder one.

    • @aj9706
      @aj9706 5 ปีที่แล้ว +1

      @@piyushmajgawali1611 but BST is, on the left it is root.

    • @anurp4173
      @anurp4173 5 ปีที่แล้ว

      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

  • @anikkhan8811
    @anikkhan8811 4 ปีที่แล้ว

    The table helps a lot to track the recursive calls. Thanks Sir :)

  • @nehachaudhary3642
    @nehachaudhary3642 7 ปีที่แล้ว +1

    You explained this really well! I had a hard time finding a solution that was easy to understand! Thank you!

  • @YogeshDarji99
    @YogeshDarji99 8 ปีที่แล้ว

    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!

  • @meganlee5897
    @meganlee5897 7 ปีที่แล้ว +20

    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

  • @akhilguptavibrantjava
    @akhilguptavibrantjava 6 ปีที่แล้ว +1

    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);

  • @krishnajha1
    @krishnajha1 4 ปีที่แล้ว

    Best explanation for this question on TH-cam

  • @Bakepichai
    @Bakepichai 7 ปีที่แล้ว +5

    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

  • @sonalathawale426
    @sonalathawale426 7 ปีที่แล้ว

    Very clear step by step explanation! Hope to see more videos from you

  • @m.a.hafeezqureshi4355
    @m.a.hafeezqureshi4355 9 ปีที่แล้ว

    Good Work Tushar. Thanks for this simple yet elegant explanation.

  • @pardeepsharma6502
    @pardeepsharma6502 7 ปีที่แล้ว

    Thanks, Sir g !! You have clarified recursion stack as well :)

  • @sparrownature9189
    @sparrownature9189 5 ปีที่แล้ว

    Hi thanks for making smaller videos. Keep making small length videos around ten minutes. And thank you for making videos.

  • @anandkulkarni2111
    @anandkulkarni2111 6 ปีที่แล้ว +3

    In order traversal plus boost.circular but ffer.of size.2 gives most efficient solution O(n) time complexity and O(1) space complexity

  • @ahrazmalik5807
    @ahrazmalik5807 3 ปีที่แล้ว

    The best video on the internet on this problem

  • @vishalrana4093
    @vishalrana4093 6 ปีที่แล้ว +13

    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 ปีที่แล้ว +2

      That'd be O(n) space, this is O(1) space.

    • @tomross2124
      @tomross2124 6 ปีที่แล้ว +5

      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 ปีที่แล้ว +2

      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 ปีที่แล้ว +1

      Inorder traversal will do the job in a simpler way. Both are O(n) space since recursion (stack) is used.

  • @wowfan007
    @wowfan007 7 ปีที่แล้ว

    Loved the explanation, esp. table visualization

  • @MohammadEhsanAnsari
    @MohammadEhsanAnsari 3 ปีที่แล้ว

    Best video on internet sir

  • @snlagr
    @snlagr 4 ปีที่แล้ว

    welcome back to th garage

  • @crafter202
    @crafter202 7 ปีที่แล้ว

    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

  • @AzatDzhanybekov
    @AzatDzhanybekov 9 ปีที่แล้ว +3

    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.

  • @ankitagarwal4914
    @ankitagarwal4914 4 ปีที่แล้ว

    Thanks for sharing !!..After watching 3 videos finally I land on this great one...

  • @uulita2129
    @uulita2129 7 ปีที่แล้ว

    Awesome!! Like the way you go through the solution. Thank you so much!

  • @KoushikChowdhury2016
    @KoushikChowdhury2016 4 ปีที่แล้ว +3

    Your code doesn't work in cases where the input is [2147483647] or [-2147483648 ,null, 2147483647]

  • @rsjsdqps7363
    @rsjsdqps7363 7 ปีที่แล้ว

    Fantastic! So simple and elegant!

  • @khaledacmilan
    @khaledacmilan 7 ปีที่แล้ว +2

    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 ปีที่แล้ว +1

      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 5 ปีที่แล้ว

      @@EngMohmdNoor We can use an iterative in order traversal, and get O(1) space

  • @muyuanchen3859
    @muyuanchen3859 ปีที่แล้ว

    best video to explain the BST.

  • @anirudhsarma4233
    @anirudhsarma4233 6 ปีที่แล้ว +6

    I might be late to this thread. But there seems to be an inorder traversal based solution. Would you cover that as well?

  • @madhukiranattivilli2321
    @madhukiranattivilli2321 3 ปีที่แล้ว

    during inorder traversal if current node data is lesser than previous data it is not a BST

  • @alicebobson2868
    @alicebobson2868 4 ปีที่แล้ว

    very good explanation, the best so far

  • @razorhxh7371
    @razorhxh7371 4 ปีที่แล้ว

    Thanks Tushar! That was super helpful

  • @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?

  • @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

  • @chittytherobot
    @chittytherobot 8 ปีที่แล้ว

    Hey Tushar - guess I bumped into a few edge cases ; in the code - why would we do only root.data

  • @kartavyaabbet123
    @kartavyaabbet123 2 ปีที่แล้ว

    Sir ji maza aha gya smj kar

  • @crisag.2698
    @crisag.2698 6 ปีที่แล้ว

    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?

  • @saicharan8675
    @saicharan8675 6 ปีที่แล้ว

    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

  • @kabitabhandari2183
    @kabitabhandari2183 6 ปีที่แล้ว

    Thanks for the code! Good explanation.

  • @ritikchail7330
    @ritikchail7330 3 ปีที่แล้ว

    Awesome walkthrough

  • @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

  • @czerox16
    @czerox16 3 ปีที่แล้ว

    shouldn't the time expense be O(h) where h is the height of the tree?

  • @tilakraj9392
    @tilakraj9392 8 ปีที่แล้ว

    This was a very good explanation.

  • @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.

  • @OverLordOfDa3rdWorld
    @OverLordOfDa3rdWorld 3 ปีที่แล้ว

    incredibly explained! thank you!

  • @e889.
    @e889. 5 ปีที่แล้ว

    Well done Gautam Gambhir

  • @aj9706
    @aj9706 5 ปีที่แล้ว

    Very well explained.Thank you

  • @s_cube8543
    @s_cube8543 5 ปีที่แล้ว

    1Kth like :D.
    Thanks for this series btw.

  • @arshamazami159
    @arshamazami159 4 ปีที่แล้ว

    great explanation thanks 👌

  • @lukeguan1397
    @lukeguan1397 4 ปีที่แล้ว

    That's the greatest explanation in youtube

  • @vivekmit
    @vivekmit 5 ปีที่แล้ว

    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 ?

  • @madhukalapala9673
    @madhukalapala9673 6 ปีที่แล้ว

    Great video... clear explanations... Thanks a lot

  • @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);
    }

  • @rroy2812
    @rroy2812 3 ปีที่แล้ว

    excellent explanation

  • @nurture_your_hobby
    @nurture_your_hobby 8 ปีที่แล้ว

    Awesome Explanation. Thanks Bro :-)

  • @paulmlyniec37
    @paulmlyniec37 6 ปีที่แล้ว

    Nice one. Really appreciate it.

  • @hanscantanhede
    @hanscantanhede 5 ปีที่แล้ว

    very well explained! Thank you.

  • @reo4465
    @reo4465 3 ปีที่แล้ว

    it's a shame that this guy doesn't make videos anymore.

  • @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.

  • @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.

  • @DAaaMan64
    @DAaaMan64 7 ปีที่แล้ว

    @3:33
    WELCOME BACK
    to the GARAGE

  • @alejandraz6080
    @alejandraz6080 8 ปีที่แล้ว

    genial, gracias desde bsas, Argentina :)

  • @liferoks26
    @liferoks26 5 ปีที่แล้ว

    Well explained bro, Thank you

  • @WowPlusWow
    @WowPlusWow 4 ปีที่แล้ว

    What is the space complexity?

  • @yuzhouwang5651
    @yuzhouwang5651 4 ปีที่แล้ว

    what if the the type of tree node is written in template, how to define infinity

  • @raj_kundalia
    @raj_kundalia 3 ปีที่แล้ว

    Thanks for the video.

  • @amitpandit3018
    @amitpandit3018 5 ปีที่แล้ว

    Can we some iterative approach to do it ?

  • @A_Millionaire_55
    @A_Millionaire_55 3 ปีที่แล้ว

    so clearly,thank you

  • @nikhilmkul
    @nikhilmkul 6 ปีที่แล้ว

    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 6 ปีที่แล้ว

      I have the same question. Were you able to make any modifications and get it to work?

  • @priyankamalviya3613
    @priyankamalviya3613 6 ปีที่แล้ว

    Thanks Tushar! I always refer to your explanations when stuck, but this code doesnt work for (1,1,null) :(

  • @codestorywithMIK
    @codestorywithMIK 7 ปีที่แล้ว

    Thanks for the video

  • @jasminewang8954
    @jasminewang8954 7 ปีที่แล้ว

    What is the function "isBSTIterative" for?

  • @AkshaySarraf1993
    @AkshaySarraf1993 7 ปีที่แล้ว

    Can't assign infinity to a number. How would you actually execute it ?

  • @ogbillity
    @ogbillity 5 ปีที่แล้ว

    you made look simple. thank you.

  • @hitec1691
    @hitec1691 5 ปีที่แล้ว +2

    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

  • @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

  • @gauravpendhari1995
    @gauravpendhari1995 5 ปีที่แล้ว

    Would you please comment your code on Github? It will be helpful for all the starters. Thanks!

  • @armandomacedo6712
    @armandomacedo6712 5 ปีที่แล้ว

    this is PreOrder traversal right?

  • @rtrs5413
    @rtrs5413 4 ปีที่แล้ว

    YOU are the best

  • @AmitSingh-ut4wt
    @AmitSingh-ut4wt 4 ปีที่แล้ว

    nice explanation

  • @reefat0904
    @reefat0904 6 ปีที่แล้ว

    Thanks. it was helpful!

  • @ArpitDhamija
    @ArpitDhamija 4 ปีที่แล้ว

    he was in Amazon , seatle

  • @ridimamittal4064
    @ridimamittal4064 4 ปีที่แล้ว

    Thank you sir , God bless: )

  • @BrianFaure1
    @BrianFaure1 7 ปีที่แล้ว

    If anyone would like to see a simple Python implementation, check out my recent lesson: th-cam.com/video/azupT01iC78/w-d-xo.html

  • @varunvikramsingh
    @varunvikramsingh 7 ปีที่แล้ว +1

    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.

  • @johndoe-eh2ol
    @johndoe-eh2ol 8 ปีที่แล้ว

    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 8 ปีที่แล้ว

      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.

  • @susmithakolli1525
    @susmithakolli1525 5 ปีที่แล้ว

    root.data >= max . I guess you missed the equal-to symbol there.

  • @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.

  • @wenyuewang5842
    @wenyuewang5842 7 ปีที่แล้ว

    you are the best :)

  • @ranesh237
    @ranesh237 2 ปีที่แล้ว

    Still the best!

  • @alexhong794
    @alexhong794 5 ปีที่แล้ว

    can you please try iteration ? Thank you

    • @aj9706
      @aj9706 5 ปีที่แล้ว

      Iteration is quite hard compared to recursive especially in tree's.

  • @prathashukla6596
    @prathashukla6596 4 ปีที่แล้ว

    This is not working on [1,1]

  • @kajalmondal9745
    @kajalmondal9745 4 ปีที่แล้ว

    Just amazing

  • @greenmug1058
    @greenmug1058 3 ปีที่แล้ว

    May god bless you

  • @derpina615
    @derpina615 3 ปีที่แล้ว

    Bruh. MIN & MAX won't work if root.val = Integer.MAX_VALUE :(

  • @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.

  • @sudipc9880
    @sudipc9880 3 ปีที่แล้ว

    Thanks sir