L48. Construct a BST from a preorder traversal | 3 Methods

Поділитися
Вставка
  • Опубліковано 27 жов 2021
  • Entire DSA Course: takeuforward.org/strivers-a2z...
    Check our Website:
    Linkedin/Instagram/Telegram: linktr.ee/takeUforward
    #treeSeries #striver #placements

КОМЕНТАРІ • 139

  • @takeUforward
    @takeUforward  2 роки тому +37

    Please like and share among friends ^ _ ^
    Find all links in description!

    • @PrinceKumar-el7ob
      @PrinceKumar-el7ob 2 роки тому

      Thanks a lot striver !! Keep uploading .

    • @tanmaisaichennagiri5543
      @tanmaisaichennagiri5543 27 днів тому +1

      Bro if we have to just return the root of the binary tree, then we can directly say that it’s the first element in that preorder array. 😛

  • @faizannasimhyder9011
    @faizannasimhyder9011 2 роки тому +78

    The red neon light kind of marker is cool. The way it disappears after every 2 sec😀

    • @mritunjay3723
      @mritunjay3723 2 роки тому +1

      no
      he makes it disappear look closely

    • @saqlainkadiri
      @saqlainkadiri 2 роки тому +1

      Which app is he using on ipad?

    • @Prakhar537
      @Prakhar537 2 роки тому +1

      @@saqlainkadiri Goodnotes

    • @yt_shubham_bgp
      @yt_shubham_bgp Рік тому +6

      @@mritunjay3723 no it disappears after you remove apple pencil from the ipad screen for more than 1 sec . It comes with good notes app

    • @misterr_stupied3747
      @misterr_stupied3747 Рік тому

      🤣

  • @TaiChiSWAG
    @TaiChiSWAG 2 роки тому +42

    I coded this by my own from your detailed explanation, started clicking on your videos first whenever I search for a problem.
    Thanks buddy thanks a lot 😊

  • @ayushm106
    @ayushm106 2 роки тому +13

    Approach 3 : Space Complexity Doubt
    Space Complexity in 3rd approach should be O(N) because of the recursive stack which takes up space of O(H) and in a skewed tree H = N.
    Here H = height of Tree
    N = Number of nodes in Tree

    • @PikasoCapture
      @PikasoCapture Рік тому +1

      recursive stack space is not an external space, thats why its O(1)

    • @anshulgoel1940
      @anshulgoel1940 10 місяців тому +2

      I think some of the videos were made earlier compared to others (like this one). At that time probably he was not considering stack space of recursion as part of space complexity. But just in case anyone is confused this will be O(H) and aligned with his thought as seen in other videos. Hope this helps.

  • @jayadubey_22
    @jayadubey_22 2 роки тому +5

    thank you so much the recursion tree really helped me to understand how return statement is working 🙏

  • @ravishkumar6060
    @ravishkumar6060 Рік тому +12

    Striver's way of explaining problems itself solves more than 50% of the problem :)

  • @pradipakshar
    @pradipakshar 7 місяців тому +3

    my mans got a lil conscious about the hair 8:18 🤣🤣🤣. Nice video as usual :)

  • @stith_pragya
    @stith_pragya 8 місяців тому +1

    Thank You So Much for this wonderful video...............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @vyankateshkulkarni4374
    @vyankateshkulkarni4374 2 роки тому +10

    the key point would be for above solution, for root.left pass root.val as bound and for root.right pass bound value as it is.
    great explanation bro. thanks

    • @MyTinTin2011
      @MyTinTin2011 Рік тому

      Thanks for this. I really missed this key point.

  • @codeman3828
    @codeman3828 2 місяці тому

    Loved the explanation

  • @rushidesai2836
    @rushidesai2836 10 днів тому

    Beautiful code!

  • @user-tk2vg5jt3l
    @user-tk2vg5jt3l 3 місяці тому

    Thank you Bhaiya

  • @Shivi32590
    @Shivi32590 4 дні тому

    thank you

  • @rahuldeshpande3516
    @rahuldeshpande3516 Рік тому +7

    The upper bound logic is brlliant

  • @nishayadav3427
    @nishayadav3427 2 роки тому

    Thank you so much for providing this series .

  • @parthsalat
    @parthsalat Рік тому +1

    Your expressions are so good that you can also go into acting 😆

  • @dank7044
    @dank7044 Місяць тому

    Did this on my own

  • @navendraagrawal
    @navendraagrawal 2 роки тому +2

    the second method is actually running faster than third one

  • @harshitjaiswal9439
    @harshitjaiswal9439 4 місяці тому

    understood.

  • @tanmayjoshi6762
    @tanmayjoshi6762 2 роки тому +11

    Hi striver, love your videos. I have one que. How is the T.C in efficient solution is O(3N) and not O(N) as it is a basic dfs traversal? Does that mean that the dfs traversals like inorder/preorder take O(3N) time instead of O(N)?

    • @dhirenparekh2646
      @dhirenparekh2646 2 роки тому

      You are right. I also got this question.

    • @AbhishekKumar-vr7sh
      @AbhishekKumar-vr7sh 2 роки тому +6

      Yeah dfs traversal also takes O(3n) time to be precise but asymptotically it's linear time complexity

    • @krishnendughosh2368
      @krishnendughosh2368 2 роки тому +1

      for N -> infinity O(3N) is simplified to O(N). So it is linear time complexity.

    • @factfactorial632
      @factfactorial632 2 роки тому +3

      I have same doubt , But i think because all the statment inside fuction just executed ones Time complexity shoud be O(N) not not O(3N)

    • @stark2461
      @stark2461 Рік тому

      It should be O(N) only because you can see each recursive function is getting executed only once not thrice.

  • @plsgivemecat
    @plsgivemecat 9 місяців тому

    Did it using stack. Python code:
    class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
    if not preorder:
    return None

    root = TreeNode(preorder[0])
    stack = [root]
    for value in preorder[1:]:
    node = TreeNode(value)
    if value < stack[-1].val:
    stack[-1].left = node
    stack.append(node)
    else:
    while stack and value > stack[-1].val:
    last = stack.pop()
    last.right = node
    stack.append(node)

    return root

  • @rakshitpuri4192
    @rakshitpuri4192 2 роки тому +8

    I used a stack to find the next greater element (right subtree)
    class Solution {
    public:
    TreeNode* create(vector& preorder, vector& nge, int i, int j){
    if(i > j){
    return NULL;
    }
    TreeNode* root = new TreeNode(preorder[i]);
    int rs = nge[i];
    root -> left = create(preorder, nge, i + 1, rs - 1);
    root -> right = create(preorder, nge, rs, j);
    return root;
    }
    TreeNode* bstFromPreorder(vector& preorder) {
    int n = preorder.size();
    stack st;
    vector nge(n);
    for(int i = n - 1; i >= 0; i--){
    while(!st.empty() and preorder[st.top()] < preorder[i]){
    st.pop();
    }
    if(st.empty()){
    nge[i] = n;
    }else nge[i] = st.top();
    st.push(i);
    }
    return create(preorder, nge, 0, n - 1);
    }
    };

    • @girikgarg8
      @girikgarg8 Рік тому

      Exactly, this is what I though of!

  • @abhinanda7049
    @abhinanda7049 2 місяці тому

    understood

  • @Jai_Jai_shri_Ram108
    @Jai_Jai_shri_Ram108 Рік тому +1

    9:58 reason why we don't consider lower bound

  • @karanbisht6359
    @karanbisht6359 Рік тому +1

    python solution for the same hope this will help someone!!!
    class Solution:
    def bstFromPreorder(self, preorder):


    h = float(inf)
    self.i = 0

    def solve(preorder,h):
    if self.i == len(preorder) or h < preorder[self.i]: return None


    root = TreeNode(preorder[self.i])
    self.i += 1
    root.left = solve(preorder,root.val)
    root.right = solve(preorder,h)

    return root

    return solve(preorder,h)class Solution:

  • @pratyayamrit7336
    @pratyayamrit7336 Рік тому +5

    Can anyone explain why do we need to take array of int rather than just an int value of i ? Thanks !

    • @anshumaan1024
      @anshumaan1024 Рік тому +2

      In java code ?
      Because in java, integer can only be passed by value, not by reference
      Hope it helps 🙂

  • @SHASHANKRUSTAGII
    @SHASHANKRUSTAGII 2 роки тому +2

    cant believe you made it so fucking easy. man

  • @Yash-uk8ib
    @Yash-uk8ib 2 роки тому +5

    sir for 2nd method (inorder one), I think it should be guarateed that the nodes will be unique otherwise, complexity will increase.

    • @takeUforward
      @takeUforward  2 роки тому +38

      Bst means nodes are unique 😅

    • @Yash-uk8ib
      @Yash-uk8ib 2 роки тому +2

      @@takeUforward oh ok!! thanks for the clarification!!

  • @raunakshalya2118
    @raunakshalya2118 2 роки тому

    Very good explanation of the 3rd method

  • @surajbaranwal56.
    @surajbaranwal56. Рік тому

    Thanks man for wonderful explanation.

  • @lavanyaprakashjampana933
    @lavanyaprakashjampana933 Рік тому +1

    we love your content and we love you...🖤

  • @somveerkhaunkar6191
    @somveerkhaunkar6191 2 роки тому +3

    Can we implement the 3rd method using stack? I think that will be more understandable..

  • @VivekSharma-eh2tv
    @VivekSharma-eh2tv 22 дні тому

    int the condition of or if i write a[i]>bound first , it gives me an error what is the reason behind this .. even the error cant be understood by me

  • @gigglezone3432
    @gigglezone3432 Рік тому

    Can we do another way for all nodes we find their correct postion to insert using bianry search and insert it - O(nlog(H))

  • @devarajm8927
    @devarajm8927 Рік тому

    Wat if we have 4 or a 3 after 7 in your example?

  • @Doraredora
    @Doraredora 2 роки тому +2

    without passing i as a reference can we do it in any other way because if we forgot to keep & symbol output will be wrong thanks in advance striver sir 🙂

    • @Cool96267
      @Cool96267 2 роки тому +1

      why did we use reference? why is it not working without reference?

    • @Doraredora
      @Doraredora 2 роки тому +3

      @@Cool96267 because while doing recursion I value has to be updated if we don't pass i by reference then output will be same values try yourself :)

    • @krishnasudan3410
      @krishnasudan3410 2 роки тому +3

      Yes, you can do by passing I as a variable of class.
      class Solution{
      int i = 0;
      //Code Here-> No need to pass i as an argument in functions.
      };

  • @ytcc2863
    @ytcc2863 Рік тому

    I really loved your content!!!

  • @virajnerlekar1501
    @virajnerlekar1501 Рік тому +2

    Can someone elaborate why the java code fails when we pass a variable instead or array in this case?? plz

    • @SilentBeing
      @SilentBeing Рік тому

      Because java does not support call by address.

  • @alephnull333
    @alephnull333 7 місяців тому

    Here to solve gate 2008 qs :)

  • @kartikking7
    @kartikking7 2 роки тому +2

    can someone tell Why is variable i passed by reference??

    • @sushmitaraj6948
      @sushmitaraj6948 2 роки тому

      Because i is traversing the index of the vector . So once an element is traversed we need to move to next element and add it into the tree

    • @mukib_khan_
      @mukib_khan_ Рік тому

      @@sushmitaraj6948 but we can also use pass by value right...because we're increasing the i value before passing it

  • @pranavdua4970
    @pranavdua4970 Рік тому

    Can bound be passed by reference?

  • @shrutiverma2594
    @shrutiverma2594 Рік тому

    Why did he make the index a list and not an integer?

  • @rishabhgupta9846
    @rishabhgupta9846 Рік тому

    understood ,able to solve by myself

  • @suryakiran2970
    @suryakiran2970 Рік тому

    Great Series

  • @rohandevaki4349
    @rohandevaki4349 2 роки тому +1

    at 3:51 why is it o(n*n) ? for every node, we are taking n time complexity? and n nodes , so O(n*n ) .

    • @CHANDANKUMAR-sg8cp
      @CHANDANKUMAR-sg8cp Рік тому +1

      O(n*n) is for extreme case or worst case as in case of skew tree for each node u have to traverse every node

    • @shivarajpatil8699
      @shivarajpatil8699 Рік тому

      @@CHANDANKUMAR-sg8cp wrong, even or skew tree the tc would be o(n). striver's first solution is talking about inserting nodes one by one, just like in the insert node in bst question. for every index in vector we would traverse the tree for logn time and insert the node at it's place. Still it would be nlogn and not n^2.

  • @user-lt2ie8ys3n
    @user-lt2ie8ys3n 11 днів тому

    why is the code so short

  • @vaalarivan_p
    @vaalarivan_p Рік тому

    5:05 - 8:40 edoc: 14:04

  • @mukib_khan_
    @mukib_khan_ Рік тому +1

    In the first method we're just connecting the node in the bst just like normally inserting a node in a bst...is this always gonna give correct preorder bst

  • @preetisahani5054
    @preetisahani5054 9 місяців тому

    I did it using stack: Maximum height of stack will be height of tree
    class Solution {
    public:
    TreeNode* bstFromPreorder(vector& preorder) {
    stack s;
    int n = preorder.size();
    if(n == 0) return NULL;
    int i = 0;
    TreeNode* root = new TreeNode(preorder[i]);
    s.push(root);
    for(int i = 1; i < n; i++) {
    TreeNode* node = s.top();
    TreeNode* newNode = new TreeNode(preorder[i]);
    if(node->val > preorder[i]) {
    s.push(newNode);
    node->left = newNode;
    }
    else if(node->val < preorder[i]) {
    while(!s.empty() && s.top()->val < preorder[i]) {
    node = s.top();
    s.pop();
    }
    s.push(newNode);
    node->right = newNode;
    }
    }
    return root;
    }
    };

    • @gorilla_coder-el6kf
      @gorilla_coder-el6kf 8 місяців тому

      hey how did you think of this solution can you provide me the thought process or intuition pls

  • @rohitchanda8461
    @rohitchanda8461 10 місяців тому

    What an explanation!

  • @akshatgoyal9113
    @akshatgoyal9113 2 роки тому

    For Method 1 and 2 it's fine but for 3rd method how will a preorder array like -> [8,5,1,7,10,2] will run it will not give correct answer with your method i think please explain

    • @chiraggupta8890
      @chiraggupta8890 2 роки тому

      Same. Did you figure it out?

    • @shivamtiwari3672
      @shivamtiwari3672 2 роки тому +1

      The preorder is wrong bcz preorder is root-left-right so left is till 7 so after that all elements should be greater than 8(root) and in this input there is 2 which is incorrect.

    • @your_name96
      @your_name96 2 роки тому

      u need to pass the index as reference or declare it as a global variable

  • @utkarshsharma6650
    @utkarshsharma6650 2 роки тому

    understooooood. thanks :)

  • @devanshgoel3433
    @devanshgoel3433 Рік тому

    thank you bhaiya!

  • @shouvikdatta6831
    @shouvikdatta6831 2 роки тому +1

    Bro, how many more videos will come of tree topic?

  • @jambajuice07
    @jambajuice07 Рік тому

    why we passed the i by reference ??

    • @abhinavgarg0077
      @abhinavgarg0077 2 місяці тому

      because the I value is changing at every iteration, that's why

  • @AiminglowNAccpble
    @AiminglowNAccpble 11 місяців тому

    5:33

  • @kartikking7
    @kartikking7 2 роки тому +1

    can anyone explain how the time complexity of 3rd solution is O(N)?....I thought it would be more than that...O(NlogN) worst case i think as the largest element will take O(logN) and for N nodes we will take O(NlogN) time in total.

  • @AiminglowNAccpble
    @AiminglowNAccpble Рік тому

    6:11

  • @parthsalat
    @parthsalat Рік тому +3

    Video starts at 6:03

  • @anjalik1012
    @anjalik1012 6 місяців тому

    Other approch ... not the range concept, no sorting even..
    class Solution {
    public:
    TreeNode* helper(vector& preorder,int ps,int pe){
    if(ps>pe)
    return NULL;
    TreeNode* root=new TreeNode(preorder[ps]);
    int r=preorder.size();
    for(int i=ps;ipreorder[ps]){
    r=i;
    break;
    }
    }
    root->left=helper(preorder,ps+1,r-1);
    root->right=helper(preorder,r,pe);
    return root;
    }
    TreeNode* bstFromPreorder(vector& preorder) {
    return helper(preorder,0,preorder.size()-1);
    }
    };
    can some one say whats the time complexity??

    • @jayakantpurushoth5650
      @jayakantpurushoth5650 Місяць тому

      cheers!, I just thought the same way,
      guess the TC is still O(n)

    • @user-qq5bb7bh5z
      @user-qq5bb7bh5z Місяць тому

      i think O(N * N) as for every node we find the next greater element and in worst case we that elemwnt can be at last so thats that, you can also check in gfg were they have discussed same aproach

    • @GodOfFaith
      @GodOfFaith 19 днів тому

      ​@@user-qq5bb7bh5zexactly this is n^2 solution

  • @momilijaz271
    @momilijaz271 2 роки тому +1

    done!

  • @sayantaniguha8519
    @sayantaniguha8519 Рік тому

    Iska time complexity smjh mein ni aya
    Backtracking ke liye alag se O(n) kiu le rahe ho

  • @shariqueahmadazizy1946
    @shariqueahmadazizy1946 Рік тому

    BST inorded is always slrted

  • @UECAshutoshKumar
    @UECAshutoshKumar 11 місяців тому +1

    Thank you sir

  • @jayyy311
    @jayyy311 2 роки тому

    💚

  • @jaiminsolanki5478
    @jaiminsolanki5478 2 роки тому

    Understood

  • @ChetanWani-be2ew
    @ChetanWani-be2ew 3 дні тому

    We can declare ' i ' as global so need to pass and it contains current value ........right.......
    code is working
    class Solution {
    static int i=0;
    public static TreeNode helper(int[] preorder,int bound){
    if(i==preorder.length || preorder[i]>bound){
    return null;
    }

    TreeNode root=new TreeNode(preorder[i++]);

    root.left=helper(preorder,root.val);
    root.right=helper(preorder,bound);

    return root;
    }
    public TreeNode bstFromPreorder(int[] preorder) {
    i=0;
    return helper(preorder,Integer.MAX_VALUE);
    }
    }

  • @user-up6sl2gq8p
    @user-up6sl2gq8p 8 місяців тому

    ,.......................

  • @yuktikashyap3374
    @yuktikashyap3374 Рік тому

    Method 3 samjh nhi aaya - tried 3 baar 😢

    • @anshumaan1024
      @anshumaan1024 Рік тому +1

      pen paper pe dry run krke dekho, ayega samaj me

    • @yuktikashyap3374
      @yuktikashyap3374 Рік тому +1

      @@anshumaan1024 yes i tried and got it
      but ig i still need more practice😅

  • @tech_wizard9315
    @tech_wizard9315 2 роки тому

    I am a DSA beginner,is your trees series enough to crack tech giant's like Microsoft linkedin level companies?

    • @PrinceKumar-el7ob
      @PrinceKumar-el7ob 2 роки тому +1

      Ofcourse it is enough

    • @Yash-uk8ib
      @Yash-uk8ib 2 роки тому +3

      practice on ur own also buddy, not everything will be served to u!

    • @parthsalat
      @parthsalat Рік тому

      You need to drop out of college for getting into tech giants

  • @girikgarg8
    @girikgarg8 Рік тому

    Done!

  • @ishangujarathi10
    @ishangujarathi10 Рік тому

    intuition op!!!

  • @chandrachurmukherjeejucse5816

    Understood.

  • @jayant8791
    @jayant8791 Рік тому

    noice

  • @satvrii
    @satvrii Рік тому

    ❤❤

  • @suvanshmahajan5902
    @suvanshmahajan5902 2 роки тому

    "us"

  • @Telugu_europe
    @Telugu_europe Рік тому

    US

  • @siddharthsaxena6495
    @siddharthsaxena6495 2 роки тому +1

    What will be the time complexity of this solution??Is this efficient??
    TreeNode* solve(TreeNode* root,int val)
    {
    if(root==NULL)
    root=new TreeNode(val);
    if(root->val>val)
    {
    root->left=solve(root->left,val);
    }
    if(root->valright=solve(root->right,val);
    }
    return root;
    }
    TreeNode* bstFromPreorder(vector& pre) {
    TreeNode* root=NULL;
    for(int i=0;i

    • @rakshitpandey7517
      @rakshitpandey7517 2 роки тому +2

      Time Complexity- O(nlogn) - as your are traversing the each node (total N nodes) using Binary search in height level and height of tree is Logn so total is nlogn.
      Space Complexity- O(H) average case...worst case is O(n)

  • @Auto_Enthusiast
    @Auto_Enthusiast Рік тому +1

    bhai tu pdata bhut bduya hai lekin , ye fake angrzi accent bhut annoying lgta hai , be natural man

  • @AmanKumarSinhaOfficial
    @AmanKumarSinhaOfficial 2 роки тому +1

    Next Video on Clarification about CP vs Development

    • @ashutoshtripathi8257
      @ashutoshtripathi8257 2 роки тому +9

      No already available bhai fltu videos ki demand q krte ho...ye sab Babbar Vagairah se kro

  • @priyankadas2531
    @priyankadas2531 7 місяців тому

    It will not work if pre Oder is 100 200 20 80 50 60 40 10

    • @priyankadas2531
      @priyankadas2531 7 місяців тому

      When my pointer is in right node 200 for 200 left part ub is 200 so 20 will be left child of 200 acc to your logic , but manually if we do 20 will be left part of top most root which is 100

  • @shubhamprasad2342
    @shubhamprasad2342 2 роки тому +8

    Hey Striver love your videos been following since a long time. kudos to your hard work man. But as i saw the video the accent with which you explain kinda seemed to me that you are being a little arrogant/over-confident on yourself. May be its just me. But wanted to give you this constructive criticism hoping for better videos in future. This is just what i felt and thought of sharing. Please Don’t get offended. Thanks ☺️

    • @takeUforward
      @takeUforward  2 роки тому +12

      Nah nah, its the confience that i have covered in the previous videos.. haha thanks man..

    • @codding32world50
      @codding32world50 Рік тому +1

      kyooo broo agar koiii best hai tum compare krlo.. striver hi hai to kyo na ho ghamand.. and i dont think its ego... if you you want to know what is ego just watch that kunal kushwahas videos you will know the difference buddy..

  • @fakeid7056
    @fakeid7056 Рік тому

    plzzz let me know why is this code incorrect on leetcode, it's accepted on gfg.
    Node* post_order(int pre[], int size)
    {
    //code here
    int i = 0;
    return buildTree(pre, 0, size-1, 0);
    }
    Node* buildTree(int pre[], int preStart, int preEnd, int i){
    if(preStart > preEnd) return NULL;
    Node* root = newNode(pre[preStart]);
    for(; i pre[preStart]){
    break;
    }
    }
    root->left = buildTree(pre, preStart+1, i-1, preStart+1);
    root->right = buildTree(pre, i, preEnd, preStart+1);
    return root;
    }

  • @chiragbansod8252
    @chiragbansod8252 4 місяці тому

    understood

  • @roopeshn3301
    @roopeshn3301 Рік тому

    Understood