L16. Diameter of Binary Tree | C++ | Java

  Рет қаралды 378,240

take U forward

take U forward

Күн бұрын

Пікірлер: 326
@takeUforward
@takeUforward 3 жыл бұрын
Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79
@democratcobra
@democratcobra 3 жыл бұрын
Likeeeeeeeeed , Shareeeeed and subscribeeeeeed......Hope you are doing extremely well.
@letmeinthefiend8522
@letmeinthefiend8522 2 жыл бұрын
sir jav root pr phuche.. to maxL=1 and maxR=4 .. to root ki height hogi 4+1 ( jab code re return kia ). or maxi hohyi (4,4+1) .. to sir answer to 5 ana chaiy na... maxi 6 kaise aarhi h
@reshmamaurya3601
@reshmamaurya3601 2 жыл бұрын
class Solution { public: int maxi = 0 ; int diameterOfBinaryTree(TreeNode* root) { if(root == NULL) return 0; int lh = height(root->left); int rh = height(root->right); maxi = max(maxi , lh+rh); return maxi; } int height(TreeNode* root){ if(root == NULL){ return 0 ; } int lh = height(root->left); int rh = height(root->right); return 1+max(lh , rh); } }; why is this code giving error ? Sir please help to find out the error i.e. I had implemented it using O(N^2) T.C. wala logic(the initial logic).
@shubhamkumar1305
@shubhamkumar1305 Жыл бұрын
​@@letmeinthefiend8522 Answer is 6. But gives 5 there will be change in some code.
@shubhamkumar1305
@shubhamkumar1305 Жыл бұрын
@@letmeinthefiend8522 Code:- if not root: return 0,maxi lh,maxi = diameterBt(root.left,maxi) rh,maxi = diameterBt(root.right,maxi) maxi = max(maxi,lh+rh) # print("maxi: ",maxi) return 1 + max(lh,rh),maxi x,diameter = diameterBt(root,maxi) print(diameter) # This will give you right answer.
@VishalGupta-xw2rp
@VishalGupta-xw2rp 2 жыл бұрын
The second last line in both the codes... diameter = max(diameter, lh+rh+1); +1 because Yes we have got the lh and rh of that node but we need to include that node itself also. Then only a whole path will be made. This video is just so nicely explained. ♥️
@VishalGupta-xw2rp
@VishalGupta-xw2rp 2 жыл бұрын
In the last line where +1 is written in both the codes.... There we are returning the height of that node itself. Like for leaf node lh=0, rh=0 but that +1 is doing all the magic.
@mahaprasadm9770
@mahaprasadm9770 2 жыл бұрын
@@VishalGupta-xw2rp I understand where you're coming from but one important piece of information you may have missed is that the path does not necessarily have to pass through the root node. So in that case, we don't need the +1.
@mr.twinklesharma5826
@mr.twinklesharma5826 2 жыл бұрын
That depends on question, Somewhere they consider the number of nodes in the longest path as diameter; on the other hand, the diameter is considered as the length of longest path which is nothing but the number of edges in the path and eventually one less than the number of nodes in the path. Ref: Leetcode & Geeksforgeeks
@shubhamkumar1305
@shubhamkumar1305 Жыл бұрын
If you written code in python, Code which I have written:- if not root: return 0,maxi lh,maxi = diameterBt(root.left,maxi) rh,maxi = diameterBt(root.right,maxi) maxi = max(maxi,lh+rh) return 1 + max(lh,rh),max depth, diameter = diameterBt(bt5,0) print(diameter) # Yu give maxi value of diameter.
@SydMohan
@SydMohan Жыл бұрын
Logic fails if the +1 is missed .... thanks @VishalGupta good catch!
@Abhishek-do8mp
@Abhishek-do8mp Жыл бұрын
This could get tricky if you think clearly, actually the recursive function is returning the height for nodes not for branches we are just using it when we are trying to make answer for root which has been generated by it's child in terms of nodes not the branches.
@studyaccount794
@studyaccount794 2 жыл бұрын
Note to self- For all the right nodes the traversal will occur in similar fashion, i.e. first right then left again, so instead of jumping directly from 6 to 7 we'll check left of 6 first then go for it's right, i.e. 7. Striver skipped that because it's self explanatory.
@dipeshsaili4468
@dipeshsaili4468 2 жыл бұрын
lol
@tilakpatidar6092
@tilakpatidar6092 3 жыл бұрын
Its a very nice series, i already know about binary tree but i just see this video for get intuition for diameter of tree because all other youtubers use pointer to solve this question and i can't understand how pointer works, but after seeing this video i got a easy solution without any pointer and solve only mechanism of finding height of a tree nice series sir👍🏻
@atjhamit
@atjhamit 2 жыл бұрын
Dude, if your language of choice is c / c++ make sure you get your pointer basics covered. Nothing justifies escaping it.
@pathikritsyam3687
@pathikritsyam3687 2 жыл бұрын
@@atjhamit True.
@kaushik.aryan04
@kaushik.aryan04 2 жыл бұрын
learn java
@atjhamit
@atjhamit 2 жыл бұрын
@@kaushik.aryan04 It would be easier to learn pointers, I suppose :'
@charlesbabbage6786
@charlesbabbage6786 7 ай бұрын
Beautifully explained!!! Love the tracing.
@rakshayadav1892
@rakshayadav1892 2 жыл бұрын
Python code: class Solution: def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: self.mx=0 self.helper(root) return self.mx def helper(self,root): if not root: return 0 l=self.helper(root.left) r=self.helper(root.right) self.mx=max(self.mx,l+r) return 1+max(l,r)
@helloworld4788
@helloworld4788 Жыл бұрын
GOAT of leetcode, thanks brother.
@chandantaneja6388
@chandantaneja6388 2 жыл бұрын
Theeeee Best explanation. I was thinking of really difficult approach by making a pair class and return both max and height. But you gave the BEST solution i ever found.
@paramsratanpal6551
@paramsratanpal6551 2 жыл бұрын
same
@btOOVipulJarial
@btOOVipulJarial Жыл бұрын
coding ninjas? That course is shit
@farhadpagdiwala1789
@farhadpagdiwala1789 3 жыл бұрын
That was a good explanation Striver. I'll watch this video one more time as I did not get the concept of why height is needed to compute the diameter.
@pranav288
@pranav288 2 жыл бұрын
we are adding heights thats why
@JohnWickea
@JohnWickea 8 ай бұрын
ah man ! go back to basics . watch video again
@anonymousvoid6356
@anonymousvoid6356 2 жыл бұрын
This is the best explanation on the internet ! This guy is a legend.
@WithRVR
@WithRVR Жыл бұрын
can use `class variable` ...... like `max_diameter` then return it some thing like this ``` class Solution { int max_diameter = 0; public int diameterOfBinaryTree(TreeNode root) { maxDepth(root); return max_diameter; } private int maxDepth(TreeNode root) { if (root == null) return 0; int left = maxDepth(root.left); int right = maxDepth(root.right); max_diameter = Math.max(max_diameter, left + right); return 1 + Math.max(left, right); } } ```
@parth_3856
@parth_3856 Жыл бұрын
//we have to add 1 to "mx=max(mx,l+r)" so it will become " mx=max(mx,l+r+1)"because the node it self also have to be included. full code-> int traversal(Node* root,int h,int l,int r,int &mx){ if(root==NULL) return 0; l=traversal(root->left,h,l,r,mx); r=traversal(root->right,h,l,r,mx); mx=max(mx,l+r+1); h=max(l,r)+1; return h; } int diameter(Node* root) { int mx=0; traversal(root,0,0,0,mx); return mx; } };
@hustler516
@hustler516 2 жыл бұрын
I was not able to do that question myself because i was missing a point that its not necessary that we need not to pass from the root........but after seeing this video all my doubt cleared ......Thanku bhyia
@prajnyasushreesangita9729
@prajnyasushreesangita9729 3 жыл бұрын
So far thr Best solution for diameter of binary tree..... In one program diameter and maxheight.... Both are done.. 👏👏👏👏👏...........
@raj-nq8ke
@raj-nq8ke 3 жыл бұрын
Then u must have not seen any other video
@tusharkuchchal2891
@tusharkuchchal2891 2 жыл бұрын
python solution class Solution: def __init__(self): self.maxi=0 def diameter(self,root): self.height(root) return self.maxi def height(self,root): if root==None: return 0 lh=self.height(root.left) rh=self.height(root.right) self.maxi=max(self.maxi,lh+rh+1) return 1+max(lh,rh)
@adamyasharma_0135
@adamyasharma_0135 11 ай бұрын
one of the best approach on this question.
@abhishekusrathe6243
@abhishekusrathe6243 3 жыл бұрын
Your tree series is amazing .having fun while watching it .keep it up bhiya .
@musicmelodies8313
@musicmelodies8313 Жыл бұрын
U are amazing . I did it myself without even looking at pseudo code. Hats off man.
@jayadubey_22
@jayadubey_22 3 жыл бұрын
on doing the dry run on my own getting more clarity thanks again 🙌
@devanshdalwadi6015
@devanshdalwadi6015 Жыл бұрын
we does not need max(maxi,lh+rh+1) in diametere?
@unknown47896
@unknown47896 10 ай бұрын
​@@devanshdalwadi6015yes it's a mistake made by striver in the brute force approach
@gandhijainamgunvantkumar6783
@gandhijainamgunvantkumar6783 2 жыл бұрын
Amazing explanation. I think there is slight mistake in the code. We have to take diameter = max(diameter, lh + rh+1). here we have to do +1 because we also have to count the node along with lh and rh. because The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes.
@sushantsharma7051
@sushantsharma7051 2 жыл бұрын
exactly bro, I was wondering the same
@vanquishersgaming138
@vanquishersgaming138 2 жыл бұрын
It counts the length of path, NOT the number of nodes. So, +1 not needed...
@vanquishersgaming138
@vanquishersgaming138 2 жыл бұрын
@@sushantsharma7051 I got what you saying. But the LeetCode question he was solving was counting the length between nodes. If you wanna count no of nodes (which is actually the diameter of tree) you can do +1, no issue.
@preetampati6140
@preetampati6140 2 жыл бұрын
That depends whether height is 0 indexed or 1 indexed.
@chandantaneja6388
@chandantaneja6388 2 жыл бұрын
@@preetampati6140 exactly just see the question requirement. like in gfg its doing +1 because ts counting the current node. But when they are not counting the current node its just slight changes. I guess you can seeby running some test cases and adjust the factor 1.
@himangshudas6244
@himangshudas6244 Жыл бұрын
Watched many videos for this question but this seemed to be the most comprehendible.
@rafaelmarcos9733
@rafaelmarcos9733 8 ай бұрын
Now I understand the solution, thank you very much!
@neerajkumarmarupalli5313
@neerajkumarmarupalli5313 2 жыл бұрын
Python Code: # O(n) time complexity # find heights of left and right sub trees and then update the value of answer def diameter(root,ans=[]): if root is None: return 0, ans lefth,leftans = diameter(root.left,ans) righth,rightans = diameter(root.right,ans) ans.append(lefth+righth) return 1+max(lefth,righth),ans height, diameters = diameter(root) print(max(diameters))
@PrinceSaluja-hs2fh
@PrinceSaluja-hs2fh Жыл бұрын
one of the best teaching style .. but i guess after explaining the concept, if you dry run the final code ..then may b student will get more clear..apart from this rest everything is perfect..
@bhaveshkumar6842
@bhaveshkumar6842 2 жыл бұрын
Very well explained as always. You sir are a legend!
@KartikeyTT
@KartikeyTT 6 ай бұрын
We can get a O(n) time complexity for the first code if we modify the code to find the height of a binary tree. Here is the code int maxDepth(TreeNode* node,int& maxi){ if(node==nullptr){ return 0 ; } int l=maxDepth(node->left,maxi); int r=maxDepth(node->right,maxi); maxi = max(maxi,l+r); // check the max diameter at each function call return 1+max(l,r); } int diameterOfBinaryTree(TreeNode* root) { int maxi =-1; // initialise maxi to -1 maxDepth(root, maxi); // pass maxi by refernce return maxi; }
@pratyush2331raj
@pratyush2331raj 8 ай бұрын
better than love babbar's approach. I am enjoying your tree series. It's truly amazing🔥🔥
@lifehustlers164
@lifehustlers164 Жыл бұрын
Completed 17/54 (31% done) !!!
@easycode3189
@easycode3189 2 жыл бұрын
simple Explanation || Easy to Understand || Thanks Alot for Valueable Effort
@SaadKarim-r6z
@SaadKarim-r6z 11 ай бұрын
diameter =max(diameter,lh+rh+1); as the node will itself include in the diameter part
@pritam7461
@pritam7461 2 жыл бұрын
diameter will be equal to max(diameter,lh+rh+1). The +1 is missing
@pankajjangra7
@pankajjangra7 2 жыл бұрын
+1 is not required here, because the question(on leetcode) says diameter as number of edges. And in a tree, the number of edges are one less than the number of nodes. So it works fine.
@sangharshpipare666
@sangharshpipare666 8 ай бұрын
I tried on my own using Java couldn't get to the solution. Nice explanation
@1712NineNine
@1712NineNine 2 жыл бұрын
wow I was thinking of creating a global variable but i never realized we can just pass by a variable by reference too by putting it in a single sized array!!!
@ramandeepsingh8464
@ramandeepsingh8464 Жыл бұрын
We can use a static variable also bro
@RajivKumar-qj9nw
@RajivKumar-qj9nw 11 ай бұрын
Node need to pass array of size 1. class Solution { private int maxDia = 0; public int diameterOfBinaryTree(TreeNode root) { getDia(root); return maxDia; } public int getDia(TreeNode root){ if(root == null) return 0; int lh = getDia(root.left); int rh = getDia(root.right); maxDia = Math.max(maxDia,lh+rh); return 1 + Math.max(lh,rh); } }
@SchrodingerMan
@SchrodingerMan 2 жыл бұрын
// brute force int height(TreeNode* root){ if(root==NULL) return 0; int x=height(root->left); int y=height(root->right); return max(x,y)+1; } int maxi=0; int diameterOfBinaryTree(TreeNode* root) { if(root==NULL) return 0; int x=height(root->left); int y= height(root->right); maxi=max(maxi,x+y); int left= diameterOfBinaryTree(root->left); int right=diameterOfBinaryTree(root->right); return maxi; }
@MischievousSoul
@MischievousSoul Жыл бұрын
Isn't this code giving error??
@kistareddy5361
@kistareddy5361 9 ай бұрын
well explained 🦁
@rohan8758
@rohan8758 Жыл бұрын
It was awesome explanation Raj bhaiyan, you did a great job.
@stith_pragya
@stith_pragya Жыл бұрын
Thank You So Much for this wonderful video................🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@yashtyagi8040
@yashtyagi8040 2 жыл бұрын
very clear explanation dry run clear all the doubt thank you sir
@VarunKumar-eq2ox
@VarunKumar-eq2ox 10 ай бұрын
please do series on binary search and greedy algorithms
@nikitakeshri9233
@nikitakeshri9233 5 ай бұрын
Beautifully explained
@user-fw4kz3bb4g
@user-fw4kz3bb4g 5 ай бұрын
u are beautiful
@Rahul_Mongia
@Rahul_Mongia Жыл бұрын
**JAVA CODE** class Solution { int diameter=0; public int diameterOfBinaryTree(TreeNode root) { if(root==null) { return 0; } helper(root); return diameter; } public int helper(TreeNode node) { if(node==null) { return 0; } int lh=helper(node.left); int rh=helper(node.right); diameter=Math.max(diameter,lh+rh); return 1+Math.max(lh,rh); } }
@cinime
@cinime 2 жыл бұрын
Understood! Such a great explanation as always, thank you very much!!
@rajsaraogi
@rajsaraogi Жыл бұрын
@12:50 to use pass by reference Code for GeekforGeek answers int diameter(Node root) { int[] diameter = new int[1]; findMax(root,diameter); return diameter[0]+1; // Your code here } int findMax(Node node, int max[]){ if(node == null) return 0; int leftH = findMax(node.left, max); int rightH = findMax(node.right, max); max[0] = Math.max(max[0],leftH + rightH); return 1 + Math.max(leftH,rightH); }
@SatyaMantha
@SatyaMantha Ай бұрын
Striver, please make string and heap series
@atharvdeshmukh8953
@atharvdeshmukh8953 2 жыл бұрын
Nice trick (0 length array) for java code at the end. I was thinking of using static variable.
@anshvashisht8519
@anshvashisht8519 2 жыл бұрын
why is array used?
@jitinroy2246
@jitinroy2246 2 жыл бұрын
@@anshvashisht8519 +1
@pqrstwxyz1175
@pqrstwxyz1175 Жыл бұрын
​@@anshvashisht8519in Java it is pass by value and not reference but array it self is a reference to a object in heap memory, where a normal variable like int, float are not pointing or referencing to any address.
@ujjwalpratap8729
@ujjwalpratap8729 3 жыл бұрын
Very well Explained , Thanks for clearing the doubts
@studyonly9622
@studyonly9622 4 ай бұрын
int helper(TreeNode*root,vector&vec){ if(root==NULL)return 0; int l = helper(root->left,vec); int r = helper(root->right,vec); vec.push_back(l+r); return 1+max(r,l); } int diameterOfBinaryTree(TreeNode* root) { vector vec; helper(root,vec); sort(vec.begin(),vec.end()); return vec[vec.size()-1]; } This is what i did before watching this video.
@vaarigupta6332
@vaarigupta6332 2 жыл бұрын
Nice solution - Simplest of all of studied so far
@nawabkhan4916
@nawabkhan4916 2 жыл бұрын
great work, and have lots of sponsor ad so that you can provide great videos.
@pervejmia8240
@pervejmia8240 2 жыл бұрын
what is the space complexity of your first approach? O(n) for recursion stack memory?
@kanishkgoel5946
@kanishkgoel5946 Жыл бұрын
Easier solution: class Solution { private: int maxDepth(TreeNode* root) { if(root==NULL) return 0; int left = maxDepth(root->left); int right = maxDepth(root->right); return 1+max(left,right); } public: int diameterOfBinaryTree(TreeNode* root) { if(root==NULL) return 0; int left = maxDepth(root->left); int right = maxDepth(root->right); int ld = diameterOfBinaryTree(root->left); int rd = diameterOfBinaryTree(root->right); return max(left+right, max(ld,rd)) ; } };
@hassankazmi5443
@hassankazmi5443 Жыл бұрын
very good job sir, beautifully simplified
@hareshnayak7302
@hareshnayak7302 6 ай бұрын
Thanks striver for this amazing video.
@bhavkushwaha
@bhavkushwaha 7 ай бұрын
Thankyou Striver, Understood!
@rishavyadav9438
@rishavyadav9438 Жыл бұрын
If you wonder how to write JAVA solution without Array int maxDiameter=0; //Declare class instance variable and using 'this' we can modify its value in function which will reflect here as well this.maxDiameter=Math.max(this.maxDiameter,leftHeight+rightHeight);
@wolfieymozart
@wolfieymozart Жыл бұрын
hi can you explain this or give the full code
@sravan8643
@sravan8643 3 жыл бұрын
My Solution: class Solution { public: int maxi; Solution(){ maxi=0; } int diameterOfBinaryTree(TreeNode* root) { maxHeight(root); return maxi; } int maxHeight(TreeNode* root){ if(root==NULL) return 0; int lst=maxHeight(root->left); int rst=maxHeight(root->right); maxi=max(maxi,lst+rst); return 1+max(lst,rst); } };
@golubhattuk01
@golubhattuk01 Жыл бұрын
thank you sir ji for this series
@codeman3828
@codeman3828 7 ай бұрын
Great video. Understood
@AmanYadav-jf1yy
@AmanYadav-jf1yy Жыл бұрын
Code for Naive approach int findh(TreeNode* root) { if(root==nullptr) return 0; int lh=findh(root->left); int rh=findh(root->right); return 1+max(lh,rh); } void solve(TreeNode* root, int &ans) { if(root==nullptr) return; int lh=findh(root->left); int rh=findh(root->right); ans=max(ans,(lh+rh)); solve(root->left,ans); solve(root->right,ans); } int diameterOfBinaryTree(TreeNode* root) { if(root==nullptr) return 0; int ans=0; solve(root,ans); return ans; }
@DeepakKumar-yc9hr
@DeepakKumar-yc9hr 3 жыл бұрын
Thankyou bhaiya for Tree Series
@funnyanimation888
@funnyanimation888 Жыл бұрын
It was really a good explanation of the algo.
@at_your_techbuddy
@at_your_techbuddy Жыл бұрын
Sir, can you please tell what is the reason you usually define helper functions like height of "private" type?
@virusdgamer8804
@virusdgamer8804 Жыл бұрын
cuz functions outside of class Solution dont need to access the height function. As you already know that it is a HELPER FUNCTION, we only want diameterOfBinaryTree func to access it and not the functions outside of the class.
@at_your_techbuddy
@at_your_techbuddy Жыл бұрын
@@virusdgamer8804 got it thanks!!
@mriduljain1981
@mriduljain1981 Жыл бұрын
completed lecture 16 of Tree playlist.
@anssha2643
@anssha2643 Жыл бұрын
Thanks for explanation. It the best I have seen so far.
@kasyapdharanikota8570
@kasyapdharanikota8570 3 жыл бұрын
very well explained
@apmotivationakashparmar722
@apmotivationakashparmar722 Ай бұрын
Thank you so much.
@26-tycm-i-durveshjagtap26
@26-tycm-i-durveshjagtap26 Жыл бұрын
Best explanation and approach so far!!!
@DeadPoolx1712
@DeadPoolx1712 Ай бұрын
UNDERSTOOD;
@Rajat_maurya
@Rajat_maurya 2 жыл бұрын
which is better practice a global variable or passing in function?
@arnabdutta4662
@arnabdutta4662 2 жыл бұрын
passing in function
@shrirambalaji2915
@shrirambalaji2915 Жыл бұрын
Thank you Brother, This series indeed helping me and Thousands of other people
@anmolverma075
@anmolverma075 Жыл бұрын
In the final code of Java , I tried taking a maximum variable instead of taking the array . Why is the code not working in this case? Cany anyone explain me this?
@ishangujarathi10
@ishangujarathi10 Жыл бұрын
love your intuition, understood completely
@vakhariyajay2224
@vakhariyajay2224 Жыл бұрын
Thank you very much. You are a genius.
@hardkapadia5633
@hardkapadia5633 10 ай бұрын
This was a fucking genius solution hats off man
@adebisisheriff159
@adebisisheriff159 10 ай бұрын
Thanks Striver!!!
@abhishekkumarsingh8603
@abhishekkumarsingh8603 3 жыл бұрын
bhaiya array banane ki jagah class variable bana denge toh bhi kaam kar hi jana chahiye kyonki motive toh yehi hai na ki multiple copy na bane recursion call pe
@takeUforward
@takeUforward 3 жыл бұрын
Hnn kese v kro krne se mtlb h :P
@whyashu
@whyashu 2 жыл бұрын
PYTHON: class Solution: def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: self.d=0 def height(root): if not root: return 0 l=height(root.left) r=height(root.right) self.d=max(self.d,l+r) return 1 + max(l,r) height(root) return self.d
@hjklmn9526
@hjklmn9526 2 жыл бұрын
Cool, I didn't understand though how the brute force solution was O(N^2). Plus, in your final solution, you could have simply maintained the max_diameter as a class level variable instead of passing a 1 element array for each recursive call..
@piyushacharya7696
@piyushacharya7696 2 жыл бұрын
global variables are not quite good to use, and since the variables are not passed by reference in java using the array of size 1 works just fine.
@hjklmn9526
@hjklmn9526 Жыл бұрын
@@piyushacharya7696 This is a single-threaded execution. And I talked about an instance variable of the class. Not global variable.
@sumit_verma_77
@sumit_verma_77 Жыл бұрын
Have you got it ?? I have same doubt because i think that code will give us everytime 0 in maxi variable.
@parthsalat
@parthsalat 2 жыл бұрын
Thanks a lot!
@namanlakhwani4752
@namanlakhwani4752 3 жыл бұрын
I'm not passing diameter variable in helper function instead defining in globally. Any disadvantage of this approach? class Solution { public: int dia=0; int diameterOfBinaryTree(TreeNode* root) { height(root); return dia; } int height(TreeNode* root){ if(root==NULL) return 0; int lh=height(root->left); int rh=height(root->right); dia=max(dia,lh+rh); return 1+max(lh,rh); } };
@rakshitpuri4192
@rakshitpuri4192 3 жыл бұрын
Use of global variable is discouraged so we should avoid them.
@adityarajsingh8110
@adityarajsingh8110 3 жыл бұрын
What you can do is pass a reference integer to diameterOfBinaryTree() so your function will look like diameterOfBinaryTree(TreeNode* root, int& maxi)
@Yash-uk8ib
@Yash-uk8ib 3 жыл бұрын
@@rakshitpuri4192 yes it is!! can u say me the reason behind it??
@adityan5302
@adityan5302 2 жыл бұрын
Python O(n2) solution Brute Force Approach Only visit if you face difficulty in writing code... def height(root): if root is None: return 0 l=height(root.left) r=height(root.right) return max(l, r)+1 def diameter(root, maxi=-9999): if root is None: return lh=height(root.left) rh=height(root.right) maxi=max(maxi, lh+rh+1) diameter(root.left, maxi) diameter(root.right, maxi) return maxi
@UECAshutoshKumar
@UECAshutoshKumar Жыл бұрын
Thank you sir
@rahulsinghshekhawat2487
@rahulsinghshekhawat2487 Жыл бұрын
Nice explanation.
@adityavaste8963
@adityavaste8963 Жыл бұрын
Great Explanation 👍
@zodiacsama7693
@zodiacsama7693 2 жыл бұрын
why we used referencing while passing diameter to the height function
@jazzbeat4443
@jazzbeat4443 2 жыл бұрын
dude explain with recursion stack memory allocation and deallocation diagrams , it will help us understand better about recursive calls
@ManishKumar-qs8xh
@ManishKumar-qs8xh 5 ай бұрын
yes, yes, find height wala code
@himanshidafouty347
@himanshidafouty347 5 ай бұрын
Understood
@bhagyashreekhairnar683
@bhagyashreekhairnar683 8 ай бұрын
Thank you
@349_rahulbhattacharya6
@349_rahulbhattacharya6 3 жыл бұрын
understood thankyou so much
@magnitegame
@magnitegame 3 жыл бұрын
striver what a easy concept and solution and different one
@auroshisray9140
@auroshisray9140 3 жыл бұрын
i love the way you teach
@nikhilkumarjamwal5322
@nikhilkumarjamwal5322 2 жыл бұрын
Nice Explanation!👍
@KartikeyTT
@KartikeyTT 3 ай бұрын
tysm sir
@spandanrastogi7144
@spandanrastogi7144 2 жыл бұрын
JAVA BRUTE FORCE : private static int findHeight(TreeNode root){ if(root == null) return 0; int leftHeight = findHeight(root.left); int rightHeight = findHeight(root.right); return 1 + Math.max(leftHeight, rightHeight); } int dia = 0; public int diameterOfBinaryTree(TreeNode root) { if(root == null) return 0; int leftHeight = findHeight(root.left); int rightHeight = findHeight(root.right); dia = Math.max(dia, leftHeight + rightHeight); diameterOfBinaryTree(root.left); diameterOfBinaryTree(root.right); return dia; }
@ankitasinha9912
@ankitasinha9912 2 жыл бұрын
Hi Shouldn't maxi =Math.max(maxi,1+lh+rh) ?
@K-Raman
@K-Raman 2 жыл бұрын
yes, because if test for only one node it return 0 diameter. So, you are correct. it should be max =Math.max(diameter[0],1+lh+rh);
@ganeshkamath89
@ganeshkamath89 2 жыл бұрын
Thanks Striver
@drdominance9392
@drdominance9392 2 жыл бұрын
Great video striver, Will maxi value remain same on going to right tree after left tree traversal? I'm not getting the point where maxi value not change after left tree traversal Someone please help 🙏🙏🙏🙏
@chandantaneja6388
@chandantaneja6388 2 жыл бұрын
think maxi is like updating each time when it encounters some greater value. make it global it will work good, so that you can access outside the function.
L17. Maximum Path Sum in Binary Tree | C++ | Java
17:50
take U forward
Рет қаралды 362 М.
Players vs Pitch 🤯
00:26
LE FOOT EN VIDÉO
Рет қаралды 133 МЛН
I thought one thing and the truth is something else 😂
00:34
عائلة ابو رعد Abo Raad family
Рет қаралды 5 МЛН
How To Choose Mac N Cheese Date Night.. 🧀
00:58
Jojo Sim
Рет қаралды 88 МЛН
Disrespect or Respect 💔❤️
00:27
Thiago Productions
Рет қаралды 43 МЛН
L15. Check for Balanced Binary Tree | C++ | Java
12:30
take U forward
Рет қаралды 357 М.
L28. Maximum Width of Binary Tree | C++ | Java
22:41
take U forward
Рет қаралды 274 М.
L27. Lowest Common Ancestor in Binary Tree | LCA | C++ | Java
14:09
take U forward
Рет қаралды 327 М.
ASHNEER GROVER GOT ROASTED BY SALMAN KHAN!
13:08
Thugesh Unfiltered
Рет қаралды 1 МЛН
L29. Children Sum Property in Binary Tree | O(N) Approach | C++ | Java
16:13
L21. Vertical Order Traversal of Binary Tree | C++ | Java
18:53
take U forward
Рет қаралды 335 М.
L38. Flatten a Binary Tree to Linked List | 3 Approaches | C++ | Java
21:51
Diameter of Binary Tree | Simple Story | Amazon | Leetcode 543
19:38
codestorywithMIK
Рет қаралды 7 М.
Players vs Pitch 🤯
00:26
LE FOOT EN VIDÉO
Рет қаралды 133 МЛН