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 Жыл бұрын
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 Жыл бұрын
@@Sumeet_100 u can use unsigned int in that everything goes fine with that
@Gyan_ki_dukaan-sx6le10 ай бұрын
ThankGod someone updated!! I have been hitting my head for last 2hours.. finally saw this comment.. thanks.
@fanigo1382 жыл бұрын
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!
@siddhantrawat15882 жыл бұрын
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
@fanigo1382 жыл бұрын
@@siddhantrawat1588 just keep practicing and revising bro.. literally no other way! Revise everyday to make sure you don't forget anything.
@siddhantrawat15882 жыл бұрын
@@fanigo138 ok bro, thanks a lot
@preetkatiyar9692 жыл бұрын
@@siddhantrawat1588 try to solve first more easy then move to medium
@siddhantrawat15882 жыл бұрын
@@preetkatiyar969 ok, thank you
@amanbhadani88402 жыл бұрын
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; } };
@namansharma73282 жыл бұрын
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.chaudhary2 жыл бұрын
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.
@parthsalat2 жыл бұрын
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)_
@parthsalat2 жыл бұрын
@@namansharma7328 Exactly, I had the same doubt...but magically it's working 😅
@parthsalat2 жыл бұрын
@Ayush Negi Mindblowing explanation! Thanks 🙏
@nikhilnagrale3 жыл бұрын
Idea of handling Overflow was amazing!!!!! I solved that using unsigned long long LOL 😂😂
@shwetanknaveen2 жыл бұрын
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
@nikhilnagrale2 жыл бұрын
@@shwetanknaveen I checked it right now it worked
@nikhilnagrale2 жыл бұрын
@@shwetanknaveen but bhaiya method is better try to understand that
@shwetanknaveen2 жыл бұрын
@@nikhilnagrale are you trying his code on git on leetcode?
@shwetanknaveen2 жыл бұрын
@@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; } };
@abhisekdas63282 жыл бұрын
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
@letsrock73542 жыл бұрын
That intro music though😍😍😍😍😍 i skip relevel part and start from there...kudos to the one who created it
Try this test case : [1,3,2,5,null,null,9,6,null,7] ...output should be 7
@U2011-n7w Жыл бұрын
awesome explanation! I earlier added this question to my doubt list but after watching this video my doubt is completely gone
@zeeshanequbal62272 жыл бұрын
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
@surajsingh-sm7qx2 жыл бұрын
Me also bro
@anuragchakraborty76072 жыл бұрын
Exactly
@theanmolmalik2 жыл бұрын
Just make you integer unsigned, those also will pass.
@SatyamKumar-bw4vi2 жыл бұрын
@@theanmolmalik Hare Krishna! Thanks
@SatyamKumar-bw4vi2 жыл бұрын
@@rohitrautela6679 Greetings Karne ka Tarika h Prabhu Ji ex Hi, Hello, like that Hare Krishna! Rohit Ji.
@abhishekgururani69932 жыл бұрын
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.
@kabiraneja76352 жыл бұрын
Thanks buddy !!!! both ideas worked
@parthsalat2 жыл бұрын
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 Жыл бұрын
Thank you, I was stuck and changing to long long made everything work.
@SatyamEdits2 жыл бұрын
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....
@jitinroy22462 жыл бұрын
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
@devathanagapuneeth72693 жыл бұрын
Hi striver. You are working very hard for us and you please take rest . Health is also important.
@takeUforward3 жыл бұрын
yeah will go off once this tree series is done!
@deepakojha84313 жыл бұрын
@@takeUforward theek hote hi Dp shuru 🙏
@sachinupreti71592 жыл бұрын
@@deepakojha8431 😄😄😄😄😄
@fffooccc9801 Жыл бұрын
@@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 Жыл бұрын
@@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
@guru16092 жыл бұрын
to prevent the overflow condition for this code you can use "long" in line 25 instead of int. :)
@mahima12192 жыл бұрын
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?
@jeevan999able2 жыл бұрын
@@mahima1219 by the time it gets stored in there it has already been reduced fit into 32 bit i.e., an int
@mrarefinmalek25242 жыл бұрын
It worked !
@pritishpattnaik46742 жыл бұрын
Thanks bro
@herculean67482 жыл бұрын
@@jeevan999able then why was it giving error while calculating, it is also 32 bit
@sanskargour66733 ай бұрын
When you cast (curr) to long long during the computation ((long long) curr * 2 + 1), the arithmetic operation is done in long long, which avoids overflow at that specific moment. Even though the result is eventually cast back to int (when stored in the queue), the key difference is that performing the multiplication in long long prevents the overflow from happening during the intermediate calculation. The overflow issue arises during the calculation itself rather than just storing the result, which is why handling the intermediate calculations in long long makes a significant difference. 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; } };
@sriramkrishnamurthy44733 жыл бұрын
Bro one suggestion , could u pls show a queue horizontally pls bro pls 🙏🙏👍👍 just helps in better visualization i think 😃
@sunilgrover41783 жыл бұрын
I can totally feel and understand you request.
@uRamPlus3 жыл бұрын
it doesn't really matter
@amanbhadani88403 жыл бұрын
Assume queue to be a hollow pipe placed vertically.
@nishantsah69812 жыл бұрын
I agree... many times i got confused his queue with stack while dry run
@sriramkrishnamurthy44732 жыл бұрын
@@amanbhadani8840 yep that surely does help now that I think of it dude !
@vashishthsharma44112 жыл бұрын
bhai aap living legend ho humanity needs more people like you
@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.
@stith_pragya Жыл бұрын
Thank You So Much for this wonderful video............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@roushankumar7684 Жыл бұрын
Kya hi mehnat kiye hai bhaiya iss video par
@AmanSingh-t2c6t Жыл бұрын
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-zm4ji6 ай бұрын
in that case if you have a skew tree with only right nodes it will also cause int overflow
@Manmohanshukla4204 ай бұрын
In that case also it's required/helpful, logic is same
@iamnottech89186 ай бұрын
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..
@roushankumar7684 Жыл бұрын
Aapke explanation ko salaam ❤
@apmotivationakashparmar7223 ай бұрын
Great Question Striver . Thank you so much !
@666Imaginative2 жыл бұрын
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; }
@tusharnain66522 жыл бұрын
You are pushing a long long into an int type queue, doesn't that give runtime error
@shwetanknaveen2 жыл бұрын
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; } };
@sumedhvichare13882 жыл бұрын
Thank you for the explanation!
@shwetanknaveen2 жыл бұрын
@@sumedhvichare1388 glad it helped 👍
@divyanshpant53182 жыл бұрын
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.
@shwetanknaveen2 жыл бұрын
@@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?
@divyanshpant53182 жыл бұрын
@@shwetanknaveen 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
@muthupandideivamsanmugam17742 жыл бұрын
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 Жыл бұрын
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.
@medhaagarwal21242 ай бұрын
I have a doubt at 21:08 where you explain why the minimal index will change. if we were to change the minimal, suppose mini_ind = 2. now if we subtract to get the cur_id = (2-2 = 0) and then when I try getting the child's index it would go back to either 1 or 2 instead of 3 and 4 as 1 and 2 practically should be assigned to NULL (the left node of index 1 did not exist thus null values!) please explain
@zee_desai7 ай бұрын
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
@yuvrajgarg1932 жыл бұрын
You have to use long long even after this trick of saving integer overflow, using int gives runtime error.
@AyushMishra-b8w9 ай бұрын
dropping a comment just to motivate you 😊😊😊 btw great series
@priyanshusolanki75037 ай бұрын
your implementation ♥♥
@satvrii Жыл бұрын
Ye bandaaa kitna awesome hai yrrrrrr 🫀🫀🫀🫀🥲🫂🫂🫂🫂🫂🫂🫂🫂🫂
@ganeshjaggineni40975 ай бұрын
NICE SUPER EXCELLENT MOTIVATED
@_Kart1k__G6 ай бұрын
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; } }
@dep24602 жыл бұрын
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
@tusharvlogs63332 жыл бұрын
@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
@shantanukumar40812 жыл бұрын
Great explanation 👍👍👍
@adityagandhi47123 жыл бұрын
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
@rakshayadav18922 жыл бұрын
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
@PriyanshiYadav-e6c11 ай бұрын
We can find the leftHeight and rightHeight of root node. Required value = 2^(min(leftHeight, rightHeight))
@PuneetMohanpuria5 ай бұрын
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
@nitinkaplas15322 жыл бұрын
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; }
@sanjays2270 Жыл бұрын
bro for taking (last index-first index+1) we can use the formula to find maxx width at the level (2**level)
@umayashaswi282229 күн бұрын
Heyyy after 3 it must be 7 right at 11:01 because 2*3+1=7 but you have written 6 ??
@Kartikey306 ай бұрын
🙂 couldn't solve by myself. this question follows very nice apoorach
@surbhirathore._7 ай бұрын
Understood!❤
@saurabhkumar5214 ай бұрын
Just curious. Can we just identify level in binary tree and get the result as 2^(max(level)) ?
@reshmah14972 жыл бұрын
Awesome explanation bro👏
@AppaniMadhavi8 ай бұрын
Its simple to use level size right
@ayushjain71303 жыл бұрын
Understood!! ✨ But I have one question. Is solving these questions on leetcode after watching videos is right or wrong?
@mohdhasnain38123 жыл бұрын
Same doubt
@namanchandra52703 жыл бұрын
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.
@tejas73792 жыл бұрын
No problem, if you understand the approach. Practice similar questions.
@rohanraj2604 Жыл бұрын
This might look easy but very tricky question Thanks #Striverbhaiya for the beautiful explanation :)
@atjhamit2 жыл бұрын
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_performs2 жыл бұрын
nope 4 / \ 5 7 \ / 8 9 Consider this tree and u will get ur ans..
@varunvishwakarma96892 жыл бұрын
This formula is valid for complete binary Tree only.....And binary tree can be of any type
@atjhamit2 жыл бұрын
@@varunvishwakarma9689 got it, thank you.
@surendradas81743 жыл бұрын
wonderful explanation !
@ishitaajaiswal3927 ай бұрын
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 .
@sujan_kumar_mitra3 жыл бұрын
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?
@takeUforward3 жыл бұрын
Not read that, try to follow leetcode.
@ssowvik2 жыл бұрын
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!!!
@AmitSingh-ut4wt2 жыл бұрын
Great Explanation. Tree series is so awesome
@DeepakGupta-ko8lh6 ай бұрын
Instead of doing minn stuff, we can simply use 2*i, 2*i+1 instead of 2*i+1, 2*i+2
@MohanaKrishnaVH2 жыл бұрын
Awesome Explanation. Understood.
@ayushgupta-ds9fg Жыл бұрын
bahut bhadiya teaching skill
@RamKumar-kz8gg3 жыл бұрын
doubt how width is 2 at 17:21. as only 1 is between 3 and 7, so the answer should be 1 !!
@takeUforward3 жыл бұрын
Am talking about indexing..
@getsnax2 жыл бұрын
Very well explained thank you striver
@thapankt3259 ай бұрын
if we just use 2*i for left, 2*i + 1 for right, with zero index tree. we can avoid over flow @takeUforward
@shivanijain21924 ай бұрын
I think we can use vertical no and at each node and then subtract it
@atifali34853 ай бұрын
Each level can can have multiple nodes too.. so it kinda fails
@paraskumar6932 жыл бұрын
@20:53 I was also thinking 1 will be minimum index for all
@samedev67927 ай бұрын
I guess the Vertical order traversal will be an easy approach. Also since we incorporate netative integers there , no overflow will occur .
@jotsinghbindra83176 ай бұрын
easier but will lead to the extra Space Complexity of using the map also will increase the time complexity
@lavanyaprakashjampana9332 жыл бұрын
WE LOVE YOUR CONTENT AND WE LOVE YOU.....🖤
@dakshkaushik2kk3 ай бұрын
The index of the first node of each level, also tells the width of that particular level. Isn't it?
@DeadPoolx17122 ай бұрын
UNDERSTOOD;
@nagavedareddy58913 жыл бұрын
Huge respect...❤👏
@AnkitSingh-tm5dp Жыл бұрын
If u stuck with runtime error please take a long long variable in place of curr_id in leeetcode same question 662.
@satendra6200 Жыл бұрын
Thanku bro
@cinime2 жыл бұрын
Understood! So amazing explanation as always, thank you very much!!
@pardhi89599 ай бұрын
bro you are genuis
@CODIFYR_GАй бұрын
why cant we use the concept of "vertical indexing" which we use on top view of binary tree. by using this, we can take the first and last element and find the answer can anyone answer my question?
@vishadjain26963 жыл бұрын
Great Explanation bhaiya!!
@ahvgkjh Жыл бұрын
Thank you very much for this vedio!
@AmanChauhan-hr1wh Жыл бұрын
you explained very well
@Telugu_europe2 жыл бұрын
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__kit2 жыл бұрын
Ans will be 3 as there is only one node(2's right child) to be counted in width.
@Learnprogramming-q7f10 ай бұрын
Thank you Bhaiya
@Shivi325906 ай бұрын
thank you
@shivanshuagrawal95325 ай бұрын
can we use Math.min(lefthheight,rightheight)*2
@shreyasinha-iitbhu80807 ай бұрын
curr_id should be of type ` long long`.
@leepakshiyadav16432 жыл бұрын
best explanation on yt
@adityapandey234 ай бұрын
Understood
@thatowlfromhogwarts4902 жыл бұрын
why cant we just find height and do 2^(height-1) as the maxm possible width??
@abhinavprakashrai8306 Жыл бұрын
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; }
@biswajitbhunia74045 ай бұрын
Cant we solve it using 2^level
@akritisharma29633 жыл бұрын
At 10:43 it should be 7 instead of 6 as 2*3 + 1 = 7.
@takeUforward3 жыл бұрын
Yeah slight typo.. hope you understand what i was trying to convey. P.S: human here
@akritisharma29633 жыл бұрын
@@takeUforward Yeah😅..Thank you so much for your reply and this tree series! Aise hi dp ki bhi leke aana 🙏🙏
@samarthkaran23142 жыл бұрын
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 ?
@bhuvaneshwarid34372 жыл бұрын
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.
@pravvur2 жыл бұрын
Great explanation
@Shantisingh-tz5sr Жыл бұрын
In GFG why this is Giving TLE?
@RahulYadav-jk7umАй бұрын
Works by just writing long long in queue index 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 first, last; for (int i = 0; i < size; i++) { int cur_id = q.front().second; TreeNode* node = q.front().first; q.pop(); if (i == 0) first = cur_id; if (i == size - 1) last = cur_id; if (node->left) { q.push({node->left, (long long)2 * cur_id + 1}); } if (node->right) { q.push({node->right, (long long)2 * cur_id + 2}); } } ans = max(ans, last - first + 1); } return ans; } };
@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
@UECAshutoshKumar Жыл бұрын
Thank you sir
@abhinavkumar82722 жыл бұрын
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.
@aswithasai40152 жыл бұрын
no it gives you wrong answer because width is max possible nodes between the extreme two node of the tree on the same level
@AyushYadav-lz5zc3 жыл бұрын
sir I am little bit confuse in the overflow part......like if we have 10^5 nodes int any tree then how it will be the part of stack over flow
@namanchandra52703 жыл бұрын
when calculating the index we are multiplying the index by two, so just imagine 2 raise to the power some big number exceed the range of the int
@tejassrivastavaK_EE_3 жыл бұрын
@@namanchandra5270 cant we just simply use long long then?
@ankitkumarghosh4623 жыл бұрын
wowwww what an explanation!.❤
@abhinavnair45774 ай бұрын
Cant we say the max width of a binary tree is the max depth of that tree multiplied by 2?
@LazyCoder204 ай бұрын
It might be possible that the max depth might not have the maxwidth at all. In a case where at the max depth/lowest level might have only one node or even if it had 2 nodes the number of nodes in between those two nodes might be lesser than some thing we got at a level above the max depth. Thus max depth * 2 would become wrong in such cases.
@jagjotsingh50232 жыл бұрын
Can't we just use pow(2,n) where n is the max depth of the tree?
@anshumaan1024 Жыл бұрын
no, this doesn't work for all test cases , like 1:58, 2nd example
@harshkushwaha50523 жыл бұрын
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
@JohnWick-kh7ow3 жыл бұрын
For 0 based indexing, Instead of doing (cur_id+1 and cur_id+2) we can do (cur_id and cur_id+1) also.
@prashantgupta23392 жыл бұрын
No we cant level 0 and 1 will work but in level 2 two nodes will have same value