L28. Maximum Width of Binary Tree | C++ | Java

Поділитися
Вставка
  • Опубліковано 19 вер 2024

КОМЕНТАРІ • 307

  • @takeUforward
    @takeUforward  3 роки тому +127

    Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79
    The test cases have been updated, so the code might tle, use long 😅

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

      It is not giving TLE but giving Runtime error which gets solved by a Long long .. Thank You so much bhaiyya for this Amazing series !!!!

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

      @@Sumeet_100 u can use unsigned int in that everything goes fine with that

    • @Gyan_ki_dukaan-sx6le
      @Gyan_ki_dukaan-sx6le 6 місяців тому

      ThankGod someone updated!! I have been hitting my head for last 2hours.. finally saw this comment.. thanks.

  • @fanigo138
    @fanigo138 2 роки тому +84

    This one was a thinker! I've solved 50+ trees problems now, but it took me more than an hour to solve this one on my own. Good one!

    • @siddhantrawat1588
      @siddhantrawat1588 Рік тому +8

      bro, i am also solving arsh's dsa sheet. I solve tree problems regularly. But, still am not able to get the logic of the problems (medium level). I almost look the solution of every problem on yt. Can you tell me how I can solve this issue?
      Thankyou

    • @fanigo138
      @fanigo138 Рік тому +20

      @@siddhantrawat1588 just keep practicing and revising bro.. literally no other way!
      Revise everyday to make sure you don't forget anything.

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

      @@fanigo138 ok bro, thanks a lot

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

      @@siddhantrawat1588 try to solve first more easy then move to medium

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

      @@preetkatiyar969 ok, thank you

  • @amanbhadani8840
    @amanbhadani8840 2 роки тому +214

    If you are getting runtime error while submiting the same code on leetcode,no need to worry,just do a minute change in the code,just typecast the value of index while pushing in the queue.You may ask since we applied a trick to tackle the integer overflow here,yes we did,but through this method we just ensure that the index we push everytime just comes under INT_MAX,and index difference is always under singed 32 bit ,i.e at max below 2^32 as stated in question itself. At everytime we are pushing (2*index+1) or (2*index+2),so its not exactly twice,its getting more than that ,thats why we need to typecast with long long.Hope its clear now.
    Below my accepted code -
    class Solution {
    public:
    int widthOfBinaryTree(TreeNode* root) {

    if(!root) return 0;

    queueq;
    q.push({root,0});
    int ans=0;
    while(!q.empty())
    {
    int size=q.size();
    int mn=q.front().second;
    int first,last;

    for(int i=0;ileft)
    q.push({node->left,(long long)curr*2+1});
    if(node->right)
    q.push({node->right,(long long)curr*2+2});
    }
    ans=max(ans,last-first+1);

    }
    return ans;

    }
    };

    • @namansharma7328
      @namansharma7328 2 роки тому +16

      Bro ...one doubt ...........we are typecasting the value while pushing in queue.......but the queue we made is to store node* and int datatype. So, would the queue store long long datatype. The code is working fine. Just wanted to know the logic. Thanks.

    • @sachin.chaudhary
      @sachin.chaudhary 2 роки тому +4

      max value of 2*curr+1 can never be more tha 6001 after subtracting the curr with the min value.
      bcoz at each level once you subtract the minimum value you have range something like [0 , 1, ..................size-1]. Since size lies in the range [1 , 3000] It should work fine.

    • @parthsalat
      @parthsalat 2 роки тому +6

      I realised that (somehow) not every variable in our code needs to be long long:
      //(Only) This needs to be long long because it'll be multiplied with 2
      long long currIndex = nodesQueue.front().second - minIndex;
      By doing this my code ran in 6ms on Leetcode _(Faster than 95% people)_

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

      @@namansharma7328 Exactly, I had the same doubt...but magically it's working 😅

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

      @Ayush Negi Mindblowing explanation! Thanks 🙏

  • @abhisekdas6328
    @abhisekdas6328 2 роки тому +21

    Hi Striver Love your work
    absolute hardwork and dedication.
    A small clarification.
    as curr_id is contant multiple for a single loop it will not create any issue if we substact with min or not or even we can substract any random number from q.front().first
    We can substract 1 just for our personal understanding and indexing nodes as 1,2,3...
    Ex:
    1
    / \
    2 3
    / \ \
    4 5 6
    case 1:substracting 1
    stack = [ [1 ,1] ] first time -> left = 1 right = 1 m = max(0,right-left +1) = 1
    stack = [ [ 2,1] , [3,2] ] 2nd time -> left = 1 right = 2 m = max(1,right-left +1) = 2
    stack = [ [4,1] , [5,2] ,[6,4] ] 3r time- > left = 1 right = 4 m = max(2,right-left +1) = 4
    case2:substracting 257
    stack = [ [1 ,1] ] first time -> left = 1 right = 1 m = max(0,right-left +1) = 1
    stack = [ [ 2,-511] , [3,-510] ] 2nd time -> left = -511 right = -510 m = max(1,right-left +1) = 2
    stack = [ [4,-1535] , [5,-1534] ,[6,-1532] ] 3rd time -> left = -1535 right = -1532 m = max(2,right-left +1) = 4
    NOTE:
    leftNode = (1-257)*2+1 = -511
    rightNode = (1-257)*2+2 = -510
    LeetCode : 662
    class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
    stack = [[root,1]]
    m = 0
    while len(stack)>0:
    n = len(stack)
    temp = []
    left = 0
    right = 0
    for i in range(n):
    top = stack[i]
    if i == 0:
    left = top[1]
    if i == n-1:
    right = top[1]
    if top[0].left != None:
    temp.append([top[0].left,(top[1]-256)*2+1])
    if top[0].right != None:
    temp.append([top[0].right,(top[1]-256)*2+2])
    stack = temp
    m = max(m,right-left+1)

    return m

  • @nikhilnagrale
    @nikhilnagrale 3 роки тому +45

    Idea of handling Overflow was amazing!!!!! I solved that using unsigned long long LOL 😂😂

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

      I don't know when did you ran the code or when leetcode updated test cases....it still throws overflow error.....I have raised PR in his repo....let's see when does he accept

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

      @@shwetanksingh5208 I checked it right now it worked

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

      @@shwetanksingh5208 but bhaiya method is better try to understand that

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

      @@nikhilnagrale are you trying his code on git on leetcode?

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

      @@nikhilnagrale I created this comment....try this too
      Your idea to prevent the overflow was great but you did one mistake.....it shouldn't be the minIndex which needs to be subtracted rather it should be the maxIndex at each level. Moreover we need not calculate first and last with comparisons for each node at a level rather first is index of left most node at the level and last is index of rightmost node at that level........more refined code is as below
      class Solution {
      public:
      int widthOfBinaryTree(TreeNode* root) {
      int size;
      //Let's suppose all the nodes are stored in array like we did in heap sort in 1 based indexing
      int minIndex,maxIndex,maxi = 1;
      queue qu;//
      qu.push(make_pair(root,0));
      pair temp;
      while(!qu.empty())
      {
      size = qu.size();
      minIndex = qu.front().second;//min index at this level will be index of leftmost node at this level
      maxIndex = qu.back().second;//max index at this level will be index of rightmost node at this level
      while(size--)
      {
      temp = qu.front();
      qu.pop();
      if(temp.first->left) qu.push(make_pair(temp.first->left,2*(temp.second-maxIndex)));//index of left child is 2x(parent's index) {1 based indexing}
      if(temp.first->right) qu.push(make_pair(temp.first->right,2*(temp.second-maxIndex)+1));//index of right child is 2x(parent's index) + 1 {1 based indexing}
      }
      maxi = max(maxi,maxIndex-minIndex+1);//number of nodes between minIndex and maxIndex including both
      }
      return maxi;

      }
      };

  • @devathanagapuneeth7269
    @devathanagapuneeth7269 3 роки тому +72

    Hi striver. You are working very hard for us and you please take rest . Health is also important.

    • @takeUforward
      @takeUforward  3 роки тому +48

      yeah will go off once this tree series is done!

    • @deepakojha8431
      @deepakojha8431 3 роки тому +18

      @@takeUforward theek hote hi Dp shuru 🙏

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

      @@deepakojha8431 😄😄😄😄😄

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

      @@takeUforward can we apply level concept here like vertical level we can store for every node and return the difference between the max and min level from map the same concept that we applied in bottom view of a tree q?

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

      @@fffooccc9801 No, we can't use that concept because multiple nodes can overlap on a line in the same level
      Try to dry run your approach on this test case
      [1,3,2,5,3,null,9]
      Correct answer is 4 for this case

  • @SatyamEdits
    @SatyamEdits 2 роки тому +20

    In code studio they have excluded all the null nodes and then calculate the width....which we can get easily by level order traversal and storing the max size of queue....

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

      same in gfg also.
      class Solution {
      // Function to get the maximum width of a binary tree.
      int getMaxWidth(Node root) {
      // Your code here
      Queue qu=new LinkedList();
      if(root==null){
      return 0;
      }
      qu.add(root);
      int length=1;
      while(!qu.isEmpty()){
      int size=qu.size();
      // for storing 1d arraylist and after completion of 1d arraylist we append this in 2d arraylist
      List sublist=new ArrayList();
      for(int i=0;i

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

    That intro music though😍😍😍😍😍 i skip relevel part and start from there...kudos to the one who created it

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

    Bro instead of using 2*i+1,2*i+2 for 0 based index, we can use 2*i , 2*i +1 because this is same as taking minimal element in the level and subtracting.

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

      Yeah it's really confusing nobody has explained it really but here is why it IS NOT the same -
      with 2*i , 2*i + 1 u might not always get your 1ST node at each level as 0 (Try it on a right skewed Tree)
      But with the explained method you will ALWAYS get your 1st node at each level as 0.

  • @sriramkrishnamurthy4473
    @sriramkrishnamurthy4473 3 роки тому +56

    Bro one suggestion , could u pls show a queue horizontally pls bro pls 🙏🙏👍👍 just helps in better visualization i think 😃

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

      I can totally feel and understand you request.

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

      it doesn't really matter

    • @amanbhadani8840
      @amanbhadani8840 2 роки тому +4

      Assume queue to be a hollow pipe placed vertically.

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

      I agree... many times i got confused his queue with stack while dry run

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

      @@amanbhadani8840 yep that surely does help now that I think of it dude !

  • @abhishekgururani6993
    @abhishekgururani6993 2 роки тому +14

    Loved it, such a beautiful question that explored the concept of serialization. In the latest it seems leetcode has added a few more testcases, so this particular solution won't pass the newly added test cases and may give an error. So make sure either you use an unsigned long long to store serials/ids. Or otherwise you can do another hack that is to, instead of subtracting the max Serial/id for a particular level you can simply subtract max Id, it'll serialize the number in -ve and -ve range has one extra space than the positive range, hence it'll work.

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

      Thanks buddy !!!! both ideas worked

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

      I realised that (somehow) not every variable in our code needs to be long long:
      //(Only) This needs to be long long because it'll be multiplied with 2
      long long currIndex = nodesQueue.front().second - minIndex;
      By doing this my code ran in 6ms on Leetcode _(Faster than 95% people)_

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

      Thank you, I was stuck and changing to long long made everything work.

  • @AmanSingh-t2c6t
    @AmanSingh-t2c6t 11 місяців тому +4

    Instead of taking values of the next nodes as (2*i+1) and (2*i+2), we can take (2*i) and (2*i+1), in this case, it is not required to subtract the minimum of nodes on the same level.

    • @az-zm4ji
      @az-zm4ji 2 місяці тому

      in that case if you have a skew tree with only right nodes it will also cause int overflow

    • @Manmohanshukla420
      @Manmohanshukla420 7 днів тому

      In that case also it's required/helpful, logic is same

  • @zeeshanequbal6227
    @zeeshanequbal6227 2 роки тому +120

    They added 2 new test cases on Leetcode making the above code fail due to integer overflow. I had to use long long even after subtracting mmin

  • @guru1609
    @guru1609 2 роки тому +34

    to prevent the overflow condition for this code you can use "long" in line 25 instead of int. :)

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

      hey could you please explain why didnt we need to change queue's datatype to long too?
      We are storing 2*curid in queue only so dont w need to make changes there?

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

      @@mahima1219 by the time it gets stored in there it has already been reduced fit into 32 bit i.e., an int

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

      It worked !

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

      Thanks bro

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

      @@jeevan999able then why was it giving error while calculating, it is also 32 bit

  • @U2011-n7w
    @U2011-n7w Рік тому +2

    awesome explanation! I earlier added this question to my doubt list but after watching this video my doubt is completely gone

  • @shwetanksingh5208
    @shwetanksingh5208 2 роки тому +23

    Your idea to prevent the overflow was great but you did one mistake.....it shouldn't be the minIndex which needs to be subtracted rather it should be the maxIndex at each level. Moreover we need not calculate first and last with comparisons for each node at a level rather first is index of left most node at the level and last is index of rightmost node at that level........more refined code is as below
    class Solution {
    public:
    int widthOfBinaryTree(TreeNode* root) {
    int size;
    //Let's suppose all the nodes are stored in array like we did in heap sort in 1 based indexing
    int minIndex,maxIndex,maxi = 1;
    queue qu;//
    qu.push(make_pair(root,0));
    pair temp;
    while(!qu.empty())
    {
    size = qu.size();
    minIndex = qu.front().second;//min index at this level will be index of leftmost node at this level
    maxIndex = qu.back().second;//max index at this level will be index of rightmost node at this level
    while(size--)
    {
    temp = qu.front();
    qu.pop();
    if(temp.first->left) qu.push(make_pair(temp.first->left,2*(temp.second-maxIndex)));//index of left child is 2x(parent's index) {1 based indexing}
    if(temp.first->right) qu.push(make_pair(temp.first->right,2*(temp.second-maxIndex)+1));//index of right child is 2x(parent's index) + 1 {1 based indexing}
    }
    maxi = max(maxi,maxIndex-minIndex+1);//number of nodes between minIndex and maxIndex including both
    }
    return maxi;

    }
    };

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

      Thank you for the explanation!

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

      @@sumedhvichare1388 glad it helped 👍

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

      So there is nothing wrong with subtracting either max or min, the only reason why this solution worked is because negative integers have one extra number. I used unsigned int and subtracted min and it worked perfectly. In the hindsight, unsigned int will give me same positive range as a long long int's positive range.

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

      @@divyanshpant5318 Just think intuitively....if you wish to protect against overflow by going on a relative scale....then what will be more protective-> Subtracting smallest value from all values or subtracting largest value from all?

    • @divyanshpant5318
      @divyanshpant5318 2 роки тому +7

      @@shwetanksingh5208 Here when u subtract largest element, all the indices will be negative. I confirmed this by printing the values. So rather than going from say 1 to 8 index values, largest element subtraction will iterate from 0 to -8, which in itself can equally likely lead to the possibility of overflow

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

    bhai aap living legend ho
    humanity needs more people like you

  • @666Imaginative
    @666Imaginative 2 роки тому +2

    code you might looking for, for overflow problem use long long
    int widthOfBinaryTree(TreeNode* root) {
    if(!root)
    return 0;
    queue q;
    q.push({root,0});
    int ans = 1;
    while(!q.empty()){
    int size = q.size();
    ans = max(ans,q.back().second-q.front().second+1);
    for(int i=0; ileft) q.push({temp.first->left,index*2+1});
    if(temp.first->right) q.push({temp.first->right,index*2+2});
    }
    }
    return ans;
    }

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

      You are pushing a long long into an int type queue, doesn't that give runtime error

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

    Simplest Approach ⬇⬇⬇⬇⬇
    int maxWidth(TreeNode *root) {
    int ans,i=-1,j=-1;
    TreeNode *node=root;
    while(node!=NULL) {
    i++;
    node=node->left;
    }
    node=root;
    while(node!=NULL) {
    j++;
    node=node->right;
    }
    ans=i

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

      Try this test case : [1,3,2,5,null,null,9,6,null,7] ...output should be 7

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

    if(node->left){
    q.push({node->left, idx*2LL+1});
    }
    if(node->right){
    q.push({node->right, idx*2LL+2});
    }
    do this on Line 31 and 33 instead before pushing it to the stack, that will fix the overflow!!!

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

    If anyone face issue of overflow just a bit change where we subtract min index we have to subtract the max index of current level where we store negative value as index for long width which solve the overflow issue. Below is the code of it.
    int widthOfBinaryTree(TreeNode* root)
    {
    if(root==NULL)
    return 0;
    queueq;
    q.push({root,0});
    int res=0;
    while(q.empty()==false)
    {
    int start=q.front().second;
    int end=q.back().second;
    res=max(res,end-start+1);
    int size=q.size();
    for(int i=0;ileft!=NULL)
    q.push({x.first->left,2*index+1});
    if(x.first->right!=NULL)
    q.push({x.first->right,2*index+2});
    }
    }
    return res;
    }

  • @yuvrajgarg193
    @yuvrajgarg193 2 роки тому +7

    You have to use long long even after this trick of saving integer overflow, using int gives runtime error.

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

    I modified the formula to 2*node and 2*node+1
    This works well on leetcode
    Besides none of those long long issues that are being pointed to in the comments
    class Solution {
    private class Pair{
    int idx;
    TreeNode node;
    Pair(int idx, TreeNode node){
    this.idx=idx;
    this.node=node;
    }
    }
    public int widthOfBinaryTree(TreeNode root) {
    Queue q=new LinkedList();
    Pair temp;
    int width=0, begin, end, size;
    q.add(new Pair(0, root));
    while(!q.isEmpty()){
    size=q.size();
    temp=q.poll();
    begin=temp.idx;
    end=temp.idx;
    if(temp.node.left!=null){
    q.add(new Pair(2*end, temp.node.left));
    }
    if(temp.node.right!=null){
    q.add(new Pair((2*end)+1, temp.node.right));
    }
    for(int i=2;iwidth){
    width=end-begin+1;
    }
    }
    return width;
    }
    }

  • @zee_desai
    @zee_desai 3 місяці тому

    You do not need to actively check for the first and last indices at a particular level
    At a particular level the first index is at the top of the queue to be processed and the last index is at the end of the queue, curr points to the last index at the end of the traversal
    def widthOfBinaryTree(self, root):
    q=deque()
    curr=root
    width=0
    q.append((curr,0))
    while q:
    n=len(q)
    top,top_idx=q[0]
    for i in range(n):
    curr,curr_idx=q.popleft()
    if curr.left:
    q.append((curr.left,2*curr_idx))
    if curr.right:
    q.append((curr.right,2*curr_idx+1))
    width=max(width,curr_idx-top_idx+1)

    return width

  • @PriyanshiYadav-e6c
    @PriyanshiYadav-e6c 7 місяців тому

    We can find the leftHeight and rightHeight of root node. Required value = 2^(min(leftHeight, rightHeight))

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

    Apart from what is explained there is much to self analyze in this question , its okay if u spent an evening on it. (and that runtime is an analysis and also why min is not always 1 u will get this one via dry run for runtime wala thing just analyze the failed testcase and use gpt yes it will take sometime u need to think what happens when levels are increased exponentially (2^n) hope I helped u a little..

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

    No need to use long long or unsigned just make min=q.back().front , it will solve
    using long long kills the logic of using new indexing for each level

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

      @Ayush Negi hey like but we never go to 2^3000 . i mean we always subtract the minimal from the indexing so at worst case of 3000 nodes we should be having number froms [0......3001] say. if i am wrong do reply. thanks

  • @ayushjain7130
    @ayushjain7130 3 роки тому +10

    Understood!! ✨
    But I have one question. Is solving these questions on leetcode after watching videos is right or wrong?

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

      Same doubt

    • @namanchandra5270
      @namanchandra5270 3 роки тому +23

      think for 10-15 min about the approach and then see the video. Here you are learning about the concept of binary tree not practicing the questions. After learning the basic concept you can go to leetcode to solve different problems on tree. I hope it will help you.

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

      No problem, if you understand the approach. Practice similar questions.

  • @shivanijain2192
    @shivanijain2192 3 дні тому

    I think we can use vertical no and at each node and then subtract it

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

    Kya hi mehnat kiye hai bhaiya iss video par

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

    I we have level, we can say that maximum number of nodes in that level is 2^(level number)
    So we can simply find number of level, and use above formula

  • @rishabhkumar8115
    @rishabhkumar8115 3 роки тому +4

    wowwww what an explanation!.❤

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

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

  • @rakshayadav1892
    @rakshayadav1892 2 роки тому +6

    Python code:
    class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
    q=[(root,0)]
    ans=0
    while q:
    n=len(q)
    mn=q[0][1]
    for i in range(n):
    curr=q[0][1]-mn
    node=q[0][0]
    q.pop(0)
    if i==0:
    first=curr
    if i==n-1:
    last=curr
    if node.left:
    q.append((node.left,2*curr+1))
    if node.right:
    q.append((node.right,2*curr+2))
    ans=max(ans,last-first+1)
    return ans

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

    Hey thanks for the series, loving it. One doubt though :
    if what you mention is actually the width of the binary tree then couldn't you simply find this out using a formula? 2^n ?

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

      nope
      4
      / \
      5 7
      \ /
      8 9
      Consider this tree and u will get ur ans..

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

      This formula is valid for complete binary Tree only.....And binary tree can be of any type

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

      @@varunvishwakarma9689 got it, thank you.

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

    Hats off to you Striver! The way youve explained such a complex approach with so ease just makes me wonder how good your Intuition is.

  • @sauravgitte6792
    @sauravgitte6792 3 місяці тому

    I guess the Vertical order traversal will be an easy approach. Also since we incorporate netative integers there , no overflow will occur .

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

      easier but will lead to the extra Space Complexity of using the map also will increase the time complexity

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

    bro for taking (last index-first index+1) we can use the formula to find maxx width at the level (2**level)

  • @adityapandey23
    @adityapandey23 2 дні тому

    Understood

  • @AnkitSingh-tm5dp
    @AnkitSingh-tm5dp Рік тому +1

    If u stuck with runtime error please take a long long variable in place of curr_id in leeetcode same question 662.

  • @DeepakGupta-ko8lh
    @DeepakGupta-ko8lh 2 місяці тому

    Instead of doing minn stuff, we can simply use 2*i, 2*i+1 instead of 2*i+1, 2*i+2

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

    NICE SUPER EXCELLENT MOTIVATED

  • @roushankumar7684
    @roushankumar7684 8 місяців тому

    Aapke explanation ko salaam ❤

  • @shreyasinha-iitbhu8080
    @shreyasinha-iitbhu8080 2 місяці тому +1

    curr_id should be of type ` long long`.

  • @thapankt325
    @thapankt325 5 місяців тому

    if we just use 2*i for left, 2*i + 1 for right, with zero index tree. we can avoid over flow @takeUforward

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

    Nice one but I guess it could be made even more simpler if you would have used the concept of vertical level as then you will be just subracting the vertical level of the last node and the first node of a particular horizontal level.

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

      Wow, I haven't thought for this one.

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

      Tried but not working, as 2 overlapping nodes on a particular horizontal level are having same column index.

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

      Won't work, as I have thought of the same approach but see leetcode example 2 you will understand why it will not work

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

    🙂 couldn't solve by myself. this question follows very nice apoorach

  • @sujan_kumar_mitra
    @sujan_kumar_mitra 3 роки тому +6

    Doubt:
    In GFG, maximum width is defined as maximum nodes present in a particular level.
    In Leetcode: maximum width is the distance between 2 corner nodes in a level(including nulls).
    Can you confirm that GFG article is false or not?

    • @takeUforward
      @takeUforward  3 роки тому +13

      Not read that, try to follow leetcode.

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

    thank you

  • @priyanshusolanki7503
    @priyanshusolanki7503 3 місяці тому

    your implementation ♥♥

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

    This might look easy but very tricky question Thanks #Striverbhaiya for the beautiful explanation :)

  • @surbhirathore._
    @surbhirathore._ 3 місяці тому

    Understood!❤

  • @AyushMishra-b8w
    @AyushMishra-b8w 5 місяців тому

    dropping a comment just to motivate you 😊😊😊 btw great series

  • @SS-pf8zm
    @SS-pf8zm Рік тому +2

    C++ Leetcode accepted Solution :
    class Solution {
    public:
    int widthOfBinaryTree(TreeNode* root) {
    if(!root)
    return 0;
    int ans=0;
    queue q;
    q.push({root, 0});
    while(!q.empty()){
    int size = q.size();
    int mmin = q.front().second; // to take the id starting from zero
    int first, last;
    for(int i=0; ileft)
    q.push({node->left, cur_id*2+1});
    if(node->right)
    q.push({node->right, cur_id*2+2});
    }
    ans = max(ans, last-first+1);
    }
    return ans;

    }
    };

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

    Great explanation 👍👍👍

  • @surendradas8174
    @surendradas8174 3 роки тому +1

    wonderful explanation !

  • @muskanmaheshwari9412
    @muskanmaheshwari9412 2 місяці тому +1

    @tuf just a recommendation, bro jis tarah se bolte ho na , vo todha samjh nhi hai, 2 se 3 baar suno tab samjh ata hai, though content is damm good. That is just my opinion. btw thank you so much for this content.

  • @JohnWick-kh7ow
    @JohnWick-kh7ow 3 роки тому +7

    For 0 based indexing, Instead of doing (cur_id+1 and cur_id+2) we can do (cur_id and cur_id+1) also.

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

      No we cant level 0 and 1 will work but in level 2 two nodes will have same value

  • @paraskumar693
    @paraskumar693 2 роки тому +4

    @20:53 I was also thinking 1 will be minimum index for all

  • @AmitSingh-ut4wt
    @AmitSingh-ut4wt 2 роки тому

    Great Explanation. Tree series is so awesome

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

    It can be simplied

  • @ayushgupta-ds9fg
    @ayushgupta-ds9fg Рік тому

    bahut bhadiya teaching skill

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

    Very well explained thank you striver

  • @saurabhkumar521
    @saurabhkumar521 23 дні тому

    Just curious. Can we just identify level in binary tree and get the result as 2^(max(level)) ?

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

    Ye bandaaa kitna awesome hai yrrrrrr 🫀🫀🫀🫀🥲🫂🫂🫂🫂🫂🫂🫂🫂🫂

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

    Understood kaka

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

    Awesome Explanation. Understood.

  • @Learnprogramming-q7f
    @Learnprogramming-q7f 6 місяців тому

    Thank you Bhaiya

  • @pardhi8959
    @pardhi8959 5 місяців тому

    bro you are genuis

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

    Its simple to use level size right

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

    if we push (root,1) intially and find cur_idx as cur_idx=q.front().second-1
    then their will be no need of making mmin integer

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

    Couldn't it also be done in the following way :
    I traverse to the left most leaf and store the level as lev1.
    Then, I traverse to the right most leaf and store the level as lev2.
    I get the minLevel = min(lev1, lev2)
    Max width = 2^(minLevel).
    Levels start from 0 index.

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

      no it gives you wrong answer because width is max possible nodes between the extreme two node of the tree on the same level

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

    At 10:24 in the vid, won't it be 7 instead of 6, at the 4th level node ?? Since it will be 2*3 + 1

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

    Thank you sir

  • @AmanChauhan-hr1wh
    @AmanChauhan-hr1wh Рік тому

    you explained very well

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

    Personal note:
    Why we are not subtracting 1 at every level from the index instead taking minimum from queue?
    coz it mignt happen only right subtree exists at a level

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

    Thank you very much for this vedio!

  • @ishitaajaiswal392
    @ishitaajaiswal392 3 місяці тому

    Hello @take U forward
    can we just not calculate the depth of the of the tree and then do 2^(depth-1) ?
    It is working for all the cases I thought of
    Please let me know if I am thinking in the right direction or not .

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

    From code we can definitely say value of first is going to be zero. So, we only need to store value of last.
    Hence, ans = max(ans, last + 1)
    In face without even storing we can solve this.
    Follow below code.

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

      /**
      * Definition for a binary tree node.
      * struct TreeNode {
      * int val;
      * TreeNode *left;
      * TreeNode *right;
      * TreeNode() : val(0), left(nullptr), right(nullptr) {}
      * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
      * };
      */
      class Solution {
      public:
      int widthOfBinaryTree(TreeNode* root) {
      if (root == NULL) {
      return 0;
      }
      int ans = 0;
      queue q;
      q.push({root, 0});
      while (!q.empty()) {
      int size = q.size();
      int mini = q.front().second;
      for (int i = 1; i ans) {
      ans = cur_id + 1;
      }
      }
      if (node->left != NULL) {
      q.push({node->left, 2 * cur_id});
      }
      if (node->right != NULL) {
      q.push({node->right, 2 * cur_id + 1});
      }
      }
      }
      return ans;
      }
      };

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

    Awesome explanation bro👏

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

    This code is giving wrong answer at 101/114 test case. Can anybody pointout possible mistakes in it?
    int widthOfBinaryTree(TreeNode* root) {
    long long int ans = 1, c = 1;
    queueq, q2;
    q.push(root);
    while(q.size())
    {
    int k = q.size();
    vectorv;
    for(int i = 0; ileft)
    {
    q.push(a->left);
    v.push_back(a->left->val);
    }
    else v.push_back(-101);
    if(a->right)
    {
    q.push(a->right);
    v.push_back(a->right->val);
    }
    else v.push_back(-101);
    }
    if(!q.size()) break;
    c *= 2;
    long long i = 0, j = v.size()-1;
    while(i=i && v[j] == -101) {j--; c--;}
    ans = max(ans, c);
    }
    return ans;
    }

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

    /**
    * Definition for a binary tree node.
    * struct TreeNode {
    * int val;
    * TreeNode *left;
    * TreeNode *right;
    * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    * };
    */
    class Solution {
    public:
    int widthOfBinaryTree(TreeNode* root) {
    if(!root) return 0;
    int ans=0;
    queue pendingNodes;//int refers to the index number of the node...in a level the nodes always have index number ranging from (1...size of level)
    //any level starts from 1 or 2 and the index of the first node present in that level.
    //in practice the nodes which exist will have range from like 2000....something
    pendingNodes.push({root,0});
    while(!pendingNodes.empty()){
    int size=pendingNodes.size();
    int minimum=pendingNodes.front().second;
    int first,last;
    for(int i=0;ileft) pendingNodes.push({node->left,(long long)2*cur+1});//when 2*cur+1 is calculated then the answer is an integer by default as 2,cur,1 aa are integers....but the result circumpassess the int_max limit...so it has to be manually typecasted to long long
    if(node->right) pendingNodes.push({node->right,(long long)2*cur+2});
    }
    //one level processed
    ans=max(ans,last-first+1);
    }
    return ans;
    }
    };

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

    understood.

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

    can we use Math.min(lefthheight,rightheight)*2

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

    understood

  • @akritisharma2963
    @akritisharma2963 3 роки тому +3

    At 10:43 it should be 7 instead of 6 as 2*3 + 1 = 7.

    • @takeUforward
      @takeUforward  3 роки тому +10

      Yeah slight typo.. hope you understand what i was trying to convey.
      P.S: human here

    • @akritisharma2963
      @akritisharma2963 3 роки тому +6

      @@takeUforward Yeah😅..Thank you so much for your reply and this tree series! Aise hi dp ki bhi leke aana 🙏🙏

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

    WE LOVE YOUR CONTENT AND WE LOVE YOU.....🖤

  • @vishadjain2696
    @vishadjain2696 3 роки тому

    Great Explanation bhaiya!!

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

    best explanation on yt

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

    Understood! So amazing explanation as always, thank you very much!!

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

    Width is calculated between any two nodes as explained initially we ignored the node in second tree in the beginning of the video
    How will skew tree with single line nodes can even be a possible test case ?

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

      It wont be a test case, skew tree will yield 0 I guess. Bcs there can never be another node in the same lvl to compare with.

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

    Great explanation

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

    Can you please clarify my doubt.
    imagine there are 3 levels in a tree. first and second levels are completely filled (1 root, 2 (root's left child), 3(roots right child)
    but the third level has starting node( 4, (2's left child) ) and (5, (3's left child)).
    what should be the solution to the above case, your program is giving 3 as the answer. but should the answer be 2 or 4 or 3 ?

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

      Ans will be 3 as there is only one node(2's right child) to be counted in width.

  • @faizahanam9354
    @faizahanam9354 3 роки тому

    class Solution {
    public:
    int widthOfBinaryTree(TreeNode* root) {
    if (!root)
    return 0;
    int ans=0;
    queueq;
    q.push({root,0});
    while(!q.empty()){
    int size=q.size();
    int min=q.front().second;
    int first,last;
    for(int i=0; ileft)
    q.push({node->left,cur_id*2+1});
    if(node->right)
    q.push({node->right,cur_id*2+2});

    }
    ans=max(ans,last-first+1);
    }
    return ans;

    }
    };
    I wrote ur cpp code but it says wrong ans:)

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

      use long long integer for further overflow

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

    Can someone explain why we did i-curmin, and not just take i ??

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

    class Solution {
    public:
    int widthOfBinaryTree(TreeNode* root) {
    queue q;
    queue secq;
    unordered_map umap;
    q.push(root);
    long long max_width = 1;
    umap[root] = 0;
    while(!q.empty())
    {
    TreeNode *curr = q.front();
    q.pop();
    if(curr->left!=NULL)
    {
    secq.push(curr->left);
    umap[curr->left] = 2 * umap[curr]+1;
    }
    if(curr->right!=NULL)
    {
    secq.push(curr->right);
    umap[curr->right] = 2 * umap[curr] + 2;
    }
    if(q.size() == 0)
    {
    if(secq.size() > 0)
    {
    TreeNode *first = secq.front();
    TreeNode *last = secq.back();
    long long f = umap[first];
    long long l = umap[last];
    long long width = l-f+1;
    umap[first] = umap[first]-f;
    umap[last] = umap[last]-f;
    max_width = max(max_width, width);
    }
    queue temp = q;
    q = secq;
    secq = temp;
    }
    }
    return max_width;
    }
    };
    Can anyone review and tell me what's wrong with the code last few testcases on LC are failing

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

    Huge respect...❤👏

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

    Can't we just use pow(2,n) where n is the max depth of the tree?

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

      no, this doesn't work for all test cases , like 1:58, 2nd example

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

    why i feel that this question is same as maximum diameter of binarytree problem

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

      The Diameter of a Binary Tree is the longest distance between ANY TWO nodes of that tree.
      The maximum width of a Binary Tree is the maximum diameter among all its LEVELS.

  • @RamKumar-kz8gg
    @RamKumar-kz8gg 3 роки тому +2

    doubt
    how width is 2 at 17:21.
    as only 1 is between 3 and 7, so the answer should be 1 !!