Check if Binary Tree is Binary Search Tree

Поделиться
HTML-код
  • Опубликовано: 8 сен 2024
  • Given a binary tree, return true if it is binary search tree else return false.
    github.com/mis...
    github.com/mis...

Комментарии • 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.

  • @pha1994
    @pha1994 5 лет назад +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 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

  • @csam11100
    @csam11100 3 года назад

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

  • @meganlee5897
    @meganlee5897 6 лет назад +20

    note:this algorithm assumes 1)there could be duplicate 2)left subtree

    • @czerox16
      @czerox16 2 года назад

      in a binary search tree there would never be duplicate, wouldn't be?

    • @saurabhgupta1595
      @saurabhgupta1595 2 года назад

      @@czerox16 NO

  • @anandkulkarni2111
    @anandkulkarni2111 5 лет назад +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

  • @akhilguptavibrantjava
    @akhilguptavibrantjava 5 лет назад +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);

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

  • @anikkhan8811
    @anikkhan8811 3 года назад

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

  • @shawnmofid7131
    @shawnmofid7131 4 года назад

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

  • @nehachaudhary3642
    @nehachaudhary3642 6 лет назад +1

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

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

  • @m.a.hafeezqureshi4355
    @m.a.hafeezqureshi4355 8 лет назад

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

  • @muyuanchen3859
    @muyuanchen3859 Год назад

    best video to explain the BST.

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

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

  • @krishnajha1
    @krishnajha1 3 года назад

    Best explanation for this question on RUclips

  • @KoushikChowdhury2016
    @KoushikChowdhury2016 4 года назад +3

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

  • @kartavyaabbet123
    @kartavyaabbet123 2 года назад

    Sir ji maza aha gya smj kar

  • @ankitagarwal4914
    @ankitagarwal4914 4 года назад

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

  • @sonalathawale426
    @sonalathawale426 6 лет назад

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

  • @sparrownature9189
    @sparrownature9189 5 лет назад

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

  • @pardeepsharma6502
    @pardeepsharma6502 6 лет назад

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

  • @wowfan007
    @wowfan007 6 лет назад

    Loved the explanation, esp. table visualization

  • @AzatDzhanybekov
    @AzatDzhanybekov 8 лет назад +3

    Good Job Tushar!

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

  • @ahrazmalik5807
    @ahrazmalik5807 3 года назад

    The best video on the internet on this problem

  • @madhukiranattivilli2321
    @madhukiranattivilli2321 3 года назад

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

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

  • @snlagr
    @snlagr 3 года назад

    welcome back to th garage

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

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

  • @rsjsdqps7363
    @rsjsdqps7363 7 лет назад

    Fantastic! So simple and elegant!

  • @uulita2129
    @uulita2129 6 лет назад

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

  • @ritikchail7330
    @ritikchail7330 3 года назад

    Awesome walkthrough

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

  • @khaledacmilan
    @khaledacmilan 6 лет назад +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 4 года назад

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

  • @MohammadEhsanAnsari
    @MohammadEhsanAnsari 3 года назад

    Best video on internet sir

  • @alicebobson2868
    @alicebobson2868 4 года назад

    very good explanation, the best so far

  • @e889.
    @e889. 5 лет назад

    Well done Gautam Gambhir

  • @rroy2812
    @rroy2812 3 года назад

    excellent explanation

  • @aj9706
    @aj9706 5 лет назад

    Very well explained.Thank you

  • @chittytherobot
    @chittytherobot 8 лет назад

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

  • @OverLordOfDa3rdWorld
    @OverLordOfDa3rdWorld 3 года назад

    incredibly explained! thank you!

  • @razorhxh7371
    @razorhxh7371 4 года назад

    Thanks Tushar! That was super helpful

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

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

  • @tilakraj9392
    @tilakraj9392 7 лет назад

    This was a very good explanation.

  • @arshamazami159
    @arshamazami159 3 года назад

    great explanation thanks 👌

  • @hanscantanhede
    @hanscantanhede 5 лет назад

    very well explained! Thank you.

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

  • @madhukalapala9673
    @madhukalapala9673 5 лет назад

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

  • @kabitabhandari2183
    @kabitabhandari2183 6 лет назад

    Thanks for the code! Good explanation.

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

  • @czerox16
    @czerox16 2 года назад

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

  • @alejandraz6080
    @alejandraz6080 7 лет назад

    genial, gracias desde bsas, Argentina :)

  • @raj_kundalia
    @raj_kundalia 3 года назад

    Thanks for the video.

  • @DAaaMan64
    @DAaaMan64 6 лет назад

    @3:33
    WELCOME BACK
    to the GARAGE

  • @kangpeng9061
    @kangpeng9061 2 года назад

    so clearly,thank you

  • @lukeguan1397
    @lukeguan1397 4 года назад

    That's the greatest explanation in youtube

  • @nurture_your_hobby
    @nurture_your_hobby 8 лет назад

    Awesome Explanation. Thanks Bro :-)

  • @ogbillity
    @ogbillity 4 года назад

    you made look simple. thank you.

  • @paulmlyniec37
    @paulmlyniec37 5 лет назад

    Nice one. Really appreciate it.

  • @AmitSingh-ut4wt
    @AmitSingh-ut4wt 4 года назад

    nice explanation

  • @liferoks26
    @liferoks26 5 лет назад

    Well explained bro, Thank you

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

  • @ranesh237
    @ranesh237 2 года назад

    Still the best!

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

  • @xxbighotshotxx
    @xxbighotshotxx 7 лет назад

    Couldn't we just do an in order traversal as well with a global variable? Wouldn't that work as well?

  • @greenmug1058
    @greenmug1058 2 года назад

    May god bless you

  • @reo4465
    @reo4465 2 года назад

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

  • @ArpitDhamija
    @ArpitDhamija 4 года назад

    he was in Amazon , seatle

  • @codestorywithMIK
    @codestorywithMIK 6 лет назад

    Thanks for the video

  • @ridimamittal4064
    @ridimamittal4064 4 года назад

    Thank you sir , God bless: )

  • @WowPlusWow
    @WowPlusWow 4 года назад

    What is the space complexity?

  • @rtrs5413
    @rtrs5413 4 года назад

    YOU are the best

  • @yuzhouwang5651
    @yuzhouwang5651 4 года назад

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

  • @reefat0904
    @reefat0904 6 лет назад

    Thanks. it was helpful!

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

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

  • @kajalmondal9745
    @kajalmondal9745 3 года назад

    Just amazing

  • @s_cube8543
    @s_cube8543 4 года назад

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

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

  • @priyankamalviya3613
    @priyankamalviya3613 5 лет назад

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

  • @amitpandit3018
    @amitpandit3018 4 года назад

    Can we some iterative approach to do it ?

  • @sudipc9880
    @sudipc9880 3 года назад

    Thanks sir

  • @BrianFaure1
    @BrianFaure1 6 лет назад

    If anyone would like to see a simple Python implementation, check out my recent lesson: ruclips.net/video/azupT01iC78/видео.html

  • @jasminewang8954
    @jasminewang8954 7 лет назад

    What is the function "isBSTIterative" for?

  • @pennapatipavan5846
    @pennapatipavan5846 4 года назад

    Thank u sir

  • @gauravpendhari1995
    @gauravpendhari1995 5 лет назад

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

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

  • @AkshaySarraf1993
    @AkshaySarraf1993 6 лет назад

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

  • @armandomacedo6712
    @armandomacedo6712 5 лет назад

    this is PreOrder traversal right?

  • @wenyuewang5842
    @wenyuewang5842 6 лет назад

    you are the best :)

  • @ankushvirmani9039
    @ankushvirmani9039 7 лет назад +1

    best

  • @payalsagar1808
    @payalsagar1808 4 года назад

    thankyou!

  • @prathashukla6596
    @prathashukla6596 4 года назад

    This is not working on [1,1]

  • @m.a.hafeezqureshi4355
    @m.a.hafeezqureshi4355 8 лет назад

    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 8 лет назад

      +Tushar Roy : The code written in java for isBST, it throws some error

  • @ArpitDhamija
    @ArpitDhamija 5 лет назад

    great !!!!!!!!!!!!!!!!!!!!!