LeetCode Day 20 - Binary Search Tree from Preorder Traversal

Binary Search Tree is an important data structure and you should be able to construct it from an array. I'm showing O(N^2) and then O(N) solution starting at 8:49
Leetcode holds a 30-day Challenge in April with a new coding interview problem appearing each day, here's contest link: leetcode.com/explore/featured...
Subscribe for more educational videos on algorithms, coding interviews and competitive programming.
- Github repository: github.com/Errichto/youtube
- Live streams on 2nd YT channel and on Twitch: / errichto2 & / errichto
- FB and Twitter: / errichto & / errichto
- Frequently Asked Questions: github.com/Errichto/youtube/w...
#Coding #Programming

Пікірлер: 112

  • @mohitthorat8580
    @mohitthorat85804 жыл бұрын

    We want Tutorial on Trees Errichto!

  • @ajays861
    @ajays8614 жыл бұрын

    A tutorial on Trees would be great!

  • @ianpan0102
    @ianpan01024 жыл бұрын

    Fantastic video, I tried to wrap my head around the more advanced solution (2nd one) with various explanations, and your video finally did it!

  • @harishrawat1205
    @harishrawat12054 жыл бұрын

    Wow Errichto! You explained it beautifully. One thing i like the most is the way you explain how to approach a problem. Keep making such videos!

  • @constructor365
    @constructor3654 жыл бұрын

    Really appreciate you starting with the simpler solution first. Helps build intuition for the more complex solutions

  • @video-vocabulary
    @video-vocabulary4 жыл бұрын

    Thank you very much, didn't understand the code of O(n) solution, but drawing at the end of the video helped me to get the idea, now I can try to code it myself

  • @brovet78
    @brovet784 жыл бұрын

    This is the best walkthrough I've seen on tree problems. Thanks!

  • @psn999100
    @psn9991004 жыл бұрын

    The way this guy explains is plain superb !! Thanks

  • @CSBVASAMMANJUNATHKASHIRAM
    @CSBVASAMMANJUNATHKASHIRAM4 жыл бұрын

    hell yes we need more of these tutorials btw great explanation

  • @ganumba11
    @ganumba114 жыл бұрын

    This was amazing explanation of binary search trees!! I love you

  • @CarrotCakeMake
    @CarrotCakeMake4 жыл бұрын

    It is fun watching you write these. I hope they give you some harder ones though, it is more fun when you don't know the answer right away.

  • @jimwoodward7293
    @jimwoodward72934 жыл бұрын

    Another outstanding video Errichto!! Additional tutorials on BST, BFS and DFS would be great.

  • @flamendless
    @flamendless4 жыл бұрын

    Please keep the explanation (step by step + drawing) like in this video's end part. It's really helpful. Even if the problem is simple.

  • @BedoEbied
    @BedoEbied4 жыл бұрын

    I really enjoyed it like a show! Go for these trees tutorial including recursion. Thanks

  • @Kranach777
    @Kranach7774 жыл бұрын

    Thanks for showing O(n) solution. It was very interesting lesson.

  • @k_co_KristidharPandit
    @k_co_KristidharPandit3 жыл бұрын

    yaa we want BST tutorial , it will be a great entertainment to learn from you bruh , take love ✨

  • @shahirabdullah5438
    @shahirabdullah54384 жыл бұрын

    you are great

  • @atibhiagrawal6460
    @atibhiagrawal64604 жыл бұрын

    I love your videos . Thanks so much for making them !

  • @__k.abhishek
    @__k.abhishek3 жыл бұрын

    You are great. Very beautiful explanation :)

  • @AllmohtarifeBlogspot
    @AllmohtarifeBlogspot4 жыл бұрын

    for my solution i used a stack to save the visited nodes, first i start by adding the root to the stack and for each element from the sequence if it's less than the top i do top->left = current. otherwise, i pop from the while the element values are small than the current value, eventually, there will be at least an element in the stack (at the end i add current to the right of the last element that had a value smaller than current)

  • @chinmaykumar7975
    @chinmaykumar79754 жыл бұрын

    You are a very good teachrt Errichto

  • @sagarverma7640
    @sagarverma76404 жыл бұрын

    Awesome explanation.... hoping to see tutorials from on Tree Data Structures :)

  • @ahsanulameensabit
    @ahsanulameensabit4 жыл бұрын

    Enjoyed it 😊, please do videos on BST construction from other traversals...

  • @bacuongcao2170
    @bacuongcao21704 жыл бұрын

    The problem here is you return a reference of a local variable to outer scope but the local variable will be deleted if it goes out of inner scope. P/s: great content :)

  • @sahilchoudhary1473

    @sahilchoudhary1473

    4 жыл бұрын

    can you explain what are you saying

  • @bacuongcao2170

    @bacuongcao2170

    4 жыл бұрын

    @@sahilchoudhary1473 In the video, Errichto got a runtime error while he is trying to return the address of the root node (a local variable) to the outer scope. The reason is that the root node which is a local variable went out of scope (the function is returned) and it's automatically released (destroyed) so you no longer access the returned value from the caller function.

  • @climbnexplore1187

    @climbnexplore1187

    4 жыл бұрын

    @@bacuongcao2170 Thx for mentioning this. Do smart pointers help (?)

  • @bacuongcao2170

    @bacuongcao2170

    4 жыл бұрын

    ​@@climbnexplore1187 Of course, you can use a shared_ptr. But a normal pointer perfectly works in this case like what Errichto did in his video

  • @kunalsinghgusain2070

    @kunalsinghgusain2070

    4 жыл бұрын

    @@bacuongcao2170 no I don't think this is the case because no matter if its local or global variable objects go to the heap, its stack that gets destroyed after method exit but variables stored in heap remain in the heap. so the method is just returning the reference to the object in the heap, which still exists. correct if I am wrong I am telling this from java point of view.

  • @5590priyank
    @5590priyank4 жыл бұрын

    A tutorial on various trees, like AVL tree, red-black tree, segment tree would be extremely helpful. There are very rare good tutorials on them

  • @jishnupramod2130
    @jishnupramod21304 жыл бұрын

    A series on Trees and Graphs would be great :)

  • @andreykarayvansky9549
    @andreykarayvansky95494 жыл бұрын

    The linear solution is very elegant. For some reason, my brain worked better with a stack than a recursion. I put on stack the first root (the result) and then if the next value is less than the stack top I put it on the stack, if not I pop from the stack to the moment it's either empty or the top is not less than the value and put again the new node on the stack.

  • @hemantranjan2297
    @hemantranjan22973 жыл бұрын

    Please Take Leetcode 30 days challenge every month!! you are a gem!

  • @imdeadshot3632
    @imdeadshot36324 жыл бұрын

    would love to refer to tutorials on trees and graphs aftere 30-day challange, enjoyed the video!

  • @ChandraShekhar-by3cd
    @ChandraShekhar-by3cd3 жыл бұрын

    Hi Errichto . On Behalf of the coding community I would like to request if you could continue the LeetCode Challenge so that we can learn from it. It will be helpful for all of us as we had our previous Leetcode Monthly Challenge. Thanks

  • @RAJPATEL-nm9nz
    @RAJPATEL-nm9nz4 жыл бұрын

    I solved using 3 methods. 1)Using stack 2)recursion 3)sorting preorder to get inorder then constructing from them.

  • @kaustavpaul6625

    @kaustavpaul6625

    4 жыл бұрын

    The third method defeats the purpose of the question. However, it's a nice trick. How did you solve using stack?

  • @that_funny_guy496
    @that_funny_guy4964 жыл бұрын

    As we were only asked to return BST root which will be formed from preorder traversal we can just write a insert() function and it works in O(n) in worst case.

  • @leetcodesolver9092
    @leetcodesolver90924 жыл бұрын

    I solved it in O(nlogn) using binary search inside recursion.

  • @samirallahverdi4948
    @samirallahverdi49484 жыл бұрын

    Very cooll explanation 👍😎

  • @baduguprakash6791
    @baduguprakash67912 жыл бұрын

    Yes we want data structures tutorial 😁

  • @jadanabil8044
    @jadanabil80443 жыл бұрын

    We want Tree tutorial Errichto. Mercy, Mercy !!🙏

  • @scayre4078
    @scayre40784 жыл бұрын

    really helpful tutorial , thx :D

  • @venkatsai5013
    @venkatsai50134 жыл бұрын

    Awesome explanation and thinking process _/\_

  • @SachinKumar-js8yd
    @SachinKumar-js8yd4 жыл бұрын

    My first idea was similar to your second one... but faced issues in implementation. ***Tutorial on Trees*** would be great

  • @dumbassopinions2270
    @dumbassopinions2270 Жыл бұрын

    best explanation

  • @mr.mystiks9968
    @mr.mystiks99684 жыл бұрын

    The final solution you have is N time and N space but seems like Morris Tree Traversal algorithm makes space constant.

  • @deepakmehrotra3426
    @deepakmehrotra34264 жыл бұрын

    Can you make tutorial on the first problem of codejam round 1B(expogo)? Please...

  • @KP-nc9gk
    @KP-nc9gk4 жыл бұрын

    "new" keyword makes the value stored in heap memory. So even if the variable holding it gets out of scope it won't get destroyed until manually deleted or the whole program is terminated.

  • @ajithkk9762
    @ajithkk97624 жыл бұрын

    above in O(n) solution you put preorder[id] > limit for boundary check , would this be just id > limit ? @Errichto

  • @Shikharchaudhary007
    @Shikharchaudhary0074 жыл бұрын

    Why not use binary search on the preorder vector and get a complexity of nlogn?

  • @akashtadwai9471
    @akashtadwai94714 жыл бұрын

    @Errictho maybe you can teach us some of your favorite topics from Computational Geometry after this series.

  • @kruschiii
    @kruschiii4 жыл бұрын

    Which keyboard layout are you using? American?

  • @GDGET72
    @GDGET724 жыл бұрын

    Could we just use a Queue instead of using limit ? That's what it seems to be doing if we are just incrementing id++.

  • @ritwikchakraborty1702
    @ritwikchakraborty17024 жыл бұрын

    More videos on tree and graphs please

  • @shridharsarraf2188
    @shridharsarraf21882 жыл бұрын

    Vision/Jarvis is such a good programmer

  • @shashanktiwari4442
    @shashanktiwari44424 жыл бұрын

    Will u not upload codejam round 1B solutions?

  • @vishalmishra1937
    @vishalmishra19374 жыл бұрын

    hello sir could u sggest what to learn in maths for prograamming

  • @ayush.kumar.13907
    @ayush.kumar.139074 жыл бұрын

    can such a method also be used for recreating BST from postorder, inorder traversal? what extra thing is needed for recreating tree from level-order traversal?

  • @Danzlh

    @Danzlh

    4 жыл бұрын

    I am thinking the same thing. For some input, it should not be possible to produce a BST with the same preorder tranversal.

  • @fbru02
    @fbru024 жыл бұрын

    Yeah and a semgnet tree tutorial would be cool as well

  • @hellowill
    @hellowill4 жыл бұрын

    I did the same thing! So handy in C++ you can use int reference, had to wrap in an array in Java. Also isnt the space O(height)?

  • @barongrmel3797

    @barongrmel3797

    4 жыл бұрын

    Yeah I think but then its also O(N) :)

  • @mihirvaghela3479
    @mihirvaghela34794 жыл бұрын

    Please make toturial on tree and recursion, *How you encounter recursion problem*

  • @SKstudio007
    @SKstudio0073 жыл бұрын

    Write c program to implement binary search tree by inserting in following 6,2,8,10,4,3,7 write c routin for find operation min.max.delete please solve the. Problem

  • @VinayKumar-rq5kd
    @VinayKumar-rq5kd4 жыл бұрын

    same apporach as valid bst or not

  • @subarukun8001
    @subarukun80014 жыл бұрын

    What Is the name of the program you use to draw?

  • @huh_wtf
    @huh_wtf4 жыл бұрын

    I solved it by regular insertion logic of BST. a simple recursion function

  • @taritgoswami3957

    @taritgoswami3957

    4 жыл бұрын

    That's good, but, you are not using the fact that we have "the preorder traversal" in hand, not any random array.

  • @piotrgorski9786

    @piotrgorski9786

    4 жыл бұрын

    But this solution is pessimistically quadratic.

  • @satviknema8629
    @satviknema86294 жыл бұрын

    14:49 "Global variable stuff like that BAD" lmao

  • @mrmrigank7154
    @mrmrigank71543 жыл бұрын

    erichto rocks

  • @abdurrubbyeinstein8480
    @abdurrubbyeinstein84804 жыл бұрын

    I want tutorial on segment trees

  • @alirezaamedeo
    @alirezaamedeo2 жыл бұрын

    There's a mistake at 8:41 : The time complexity of inefficient algorithm in N*Log(N) not N**2.

  • @audiogear4412
    @audiogear44124 жыл бұрын

    Plus blue yeti sucks, get a pro audio gear, you deserve it. You are such a talent.

  • @mattdukeshire3837
    @mattdukeshire38374 жыл бұрын

    Code Jam vids?

  • @rajdave9862
    @rajdave98624 жыл бұрын

    What is difference between low+high/2. And low +(high-low)/2 in binary search? Please tell

  • @jinxblaze

    @jinxblaze

    4 жыл бұрын

    The latter does not cause integer overflow

  • @ajays861

    @ajays861

    4 жыл бұрын

    kzread.info/dash/bejne/eYlrptKgeKy0h7Q.html Watch this video! the second formula will not cause an integer overflow.

  • @rajdave9862

    @rajdave9862

    4 жыл бұрын

    @@ajays861 thank you so much, buddy ❣️, god bless you, thanks again.

  • @rajdave9862

    @rajdave9862

    4 жыл бұрын

    @@jinxblaze thank you so much

  • @ajays861

    @ajays861

    4 жыл бұрын

    @@rajdave9862 no mention 😇

  • @philtoa334
    @philtoa3344 жыл бұрын

    YES

  • @manmeetsingh1194
    @manmeetsingh11944 жыл бұрын

    Tutorial on Trees is needed too much

  • @sumanthgaduputi1485
    @sumanthgaduputi14854 жыл бұрын

    Tutorial on Graphs and trees please

  • @srikanthnarapureddy4580
    @srikanthnarapureddy45804 жыл бұрын

    The problem can be simply solved in O(n) by performing BST insertion for every element from left to right of preorder array..

  • @PiyushKumar-qj8ue

    @PiyushKumar-qj8ue

    4 жыл бұрын

    Think carefully, it won't be O(n). In worst case it will be O(n^2).

  • @srikanthnarapureddy4580

    @srikanthnarapureddy4580

    4 жыл бұрын

    Yeah thanks for correcting me

  • @Thepankaz1
    @Thepankaz12 жыл бұрын

    How can you simply know that bounds will work like that, he didn't even try to break his approach. it simply worked like magic.

  • @abhirajsingh8138
    @abhirajsingh81384 жыл бұрын

    more trees and graph tuts plz'

  • @irsathkareem7513
    @irsathkareem75134 жыл бұрын

    yes, we want tutorials on trees and graphs..............

  • @tonymok535
    @tonymok5354 жыл бұрын

    I implemented it using iterative dfs, with upper and lower limit for each node. But it’s slower then your approach haha Ps just realised lower limit is not useful here

  • @rajarshibose5122

    @rajarshibose5122

    4 жыл бұрын

    That's the key observation .I have done the same thing ,later realised that.

  • @yunjiehong4649
    @yunjiehong46494 жыл бұрын

    As a Competitive programmer, you may be not familiar with ‘new’ operator.

  • @sirajummunir2001
    @sirajummunir20014 жыл бұрын

    Why Don't You make tutorials on programming??

  • @Aswin255
    @Aswin2554 жыл бұрын

    ayy i'm early.

  • @VARUN-pk7xq
    @VARUN-pk7xq3 жыл бұрын

    How can I be like you ,what course should I do ,plz sir help me plz suggest me something ! That can I follow in daily basis to improve coding 🙏🙏🙏🙏🙏♥️♥️♥️♥️

  • @Naton
    @Naton4 жыл бұрын

    logical but implementation is brain teasing

  • @wengeance8962
    @wengeance89624 жыл бұрын

    I wish someone could help me with a python implementation of this algorithm, its very elegant

  • @bismeetsingh352

    @bismeetsingh352

    3 жыл бұрын

    class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: def helper(limit): nonlocal idx if idx==len(preorder) or preorder[idx]>limit: return None root_value=preorder[idx] root=TreeNode(root_value) idx+=1 root.left=helper(root_value) root.right=helper(limit) return root idx=0 return helper(float("inf"))

  • @monitthakkar3173
    @monitthakkar31734 жыл бұрын

    make same video for only binary tree not bst

  • @kabboghosh1853
    @kabboghosh18534 жыл бұрын

    tutorials on trees

  • @audiogear4412
    @audiogear44124 жыл бұрын

    I can't stop laughing when I see TreeNode root = TreeNode(root_value)

  • @sirajummunir2001
    @sirajummunir20014 жыл бұрын

    Can I be Your Friend Please.....

  • @davithov
    @davithov3 ай бұрын

    You're an amazing competitive programmer, but probably you should learn the c++ language a bit. For example, it was surprising to me that you didn't know about local variable's lilfetime and that it is an issue to return reference to it as it is already destroyed.

  • @satishkumarpatra4896
    @satishkumarpatra48964 жыл бұрын

    first cmnt.

  • @shresthmishra9329
    @shresthmishra93294 жыл бұрын

    Blah Blah Blah

  • @scepticgene
    @scepticgene4 жыл бұрын

    Python please !!!

  • @shivaraj-bh

    @shivaraj-bh

    4 жыл бұрын

    I have written a python3 implementation...O(N), it basically remembers the minimum possible value and maximum possible value at a given node and decides whether the current node fits in the position. check it out here: pastebin.com/MrNg1EiF