Diameter of a Binary Tree (Code/ Algorithm)

  Рет қаралды 94,791

Vivekanand Khyade - Algorithm Every Day

Vivekanand Khyade - Algorithm Every Day

Күн бұрын

Пікірлер: 183
@irynasherepot9882
@irynasherepot9882 5 жыл бұрын
This is a great video, perfect speed for someone new and with English second language. Thank you for making it so easy to understand!
@unboxingzindagi9972
@unboxingzindagi9972 4 жыл бұрын
Totally Agree.He is so real explanation ,no hussle and .He is so real!!
@tsupreetsingh
@tsupreetsingh 4 жыл бұрын
True
@opeyemijonah9480
@opeyemijonah9480 2 жыл бұрын
I appreciate your solution, it was the only one I could understand on this topic. FYI, I translated this to JavaScript. However, for the final result portion, I removed '+1' from the height equation in the diameter function because the height function already includes a +1 to the left or right tree. It passed all cases when I did that.
@User-nq9ee
@User-nq9ee Жыл бұрын
Probably, you solved on leet code, where is not nodes but the most number of edges. which are 1 less than the number of nodes.
@praveenchouhan6388
@praveenchouhan6388 4 жыл бұрын
your way of slow explanation is very effective and efficient as these recursive problems are understood best when someone explains slowly other wise its difficult to keep track of recursive call flows, so keep going the way you are and keeping sharing knowledge like you are doing now.
@TheSridharraj
@TheSridharraj 3 жыл бұрын
Just one correction or making everyone aware. when calculating the height of the tree, you should include the root too. hence in the diameter math you can simply do return Math.max(leftHeight+rightHeight , Math.max(lDiameter, rDiameter))
@kulaudo
@kulaudo 3 жыл бұрын
True, with the video from the same problem description for the height would be confusing.
@Adityasharma-oe8zp
@Adityasharma-oe8zp 3 жыл бұрын
Sir you have perfect explanation for every problem.....you can write your own book....you explain better than best books out there of data structures
@mareimorsy3182
@mareimorsy3182 2 жыл бұрын
I watched 10s of videos which is explaining the same problem, your video is the only one that made me finally get it, You're an awesome teacher, keep going
@ABU_BEKIR_SIDDIK
@ABU_BEKIR_SIDDIK 6 жыл бұрын
Just play this video 1.5 speed.
@agyatanonymous3995
@agyatanonymous3995 6 жыл бұрын
2x works as just perfectly!
@humblecoder9119
@humblecoder9119 5 жыл бұрын
LOL ! But, he is a great teacher and doing awesome job ! Thank you !
@ishan_kumar
@ishan_kumar 5 жыл бұрын
I wish there is 3X option.
@sandeepvedavyas8701
@sandeepvedavyas8701 4 жыл бұрын
@@ishan_kumar press ctrl + shift + j. In the console window type document.getElementsByTagName("video")[0].playbackRate = 3.0
@kartikaygoel3042
@kartikaygoel3042 4 жыл бұрын
@@ishan_kumar U can also add video speed controller extension
@pahehepaa4182
@pahehepaa4182 4 жыл бұрын
Very good explanation! The other guys were confusing until I stumbled upon this guy's video.
@staffeng
@staffeng 3 жыл бұрын
One thing to note here is the repeated calculation of height is inefficient. So if you're coding it out, you should return a pair "height+diameter" for every subtree. But I understand that Vivekanand (OP, instructor) here omitted it because it distracts us from the main goal of finding the diameter here.
@aruneshsrivastava7154
@aruneshsrivastava7154 2 жыл бұрын
correct solution , other than the fact is maximum diameter could be number of edges in the path , not the number of nodes, in that case we don't have to add extra 1 to the heights
@griffinbaker9792
@griffinbaker9792 2 жыл бұрын
Implementation in JS..it works! Thank you sir. function binaryTreeDiameter(tree) { // Write your code here. if (!tree) return 0; const heightOfLeft = height(tree.left); const heightOfRight = height(tree.right); const heightOfNode = 1 + Math.max(heightOfLeft, heightOfRight); const diameterLeft = binaryTreeDiameter(tree.left); const diameterRight = binaryTreeDiameter(tree.right); const pathThroughRoot = heightOfRight + heightOfLeft; const maxDiameterBelow = Math.max(diameterLeft, diameterRight); return Math.max(maxDiameterBelow, pathThroughRoot); } function height(tree) { if (!tree) return 0; const left = height(tree.left); const right = height(tree.right); return 1 + Math.max(left, right); }
@AbhiKumar-yk9sr
@AbhiKumar-yk9sr 2 жыл бұрын
Sir Your explanation is nice , every person can easily understand
@ytuser659
@ytuser659 4 жыл бұрын
Great explanation, loved it. But I just want to make a point that this is not the most efficient solution. For a given node, we are calculating the height and the diameter separately when you can get the diameter while calculating the height.
@kasyapdharanikota8570
@kasyapdharanikota8570 3 жыл бұрын
that is true , height can be calculated while calculating the diameter by just adding one more parameter .
@jeezradz
@jeezradz 4 жыл бұрын
just wow! I was struggling so much and you made this crystal clear. Thankyou! Great video~!
@opeyemijonah8530
@opeyemijonah8530 2 жыл бұрын
You are blessed with teaching. I wish I had found this video earlier.
@ChandraShekhar-by3cd
@ChandraShekhar-by3cd 4 жыл бұрын
You Explain like a PRO..Thanks for such a detailed explanation!
@jacktrainer4387
@jacktrainer4387 4 жыл бұрын
Most thorough explanation out there! Great job!
@pauldaviddavies
@pauldaviddavies 3 жыл бұрын
Vivek, that is a great video. Great explanation that is very much personalized for everyone. Thank you!
@jhanvibatra828
@jhanvibatra828 3 жыл бұрын
Best Explaination so far. Thankyou sir
@elebs_d
@elebs_d 2 жыл бұрын
Thank youu. I was really struggling to understand this and you explained it beautifully
@thelasttimeitookashowerwas7069
@thelasttimeitookashowerwas7069 4 жыл бұрын
finding a recursive solution is extremely tough ):
@nivedithat4745
@nivedithat4745 4 жыл бұрын
I kinda like how creative your username is😂... Made my day😂😂
@jatin1688
@jatin1688 3 жыл бұрын
Hmm it is difficult to find recursive one
@K_EC_AushoRoup
@K_EC_AushoRoup 4 жыл бұрын
Thanks sir, I was just forgetting the 2nd case when diameter is not passing through the root. Not I got it. Thanks
@saurabhsen3560
@saurabhsen3560 4 жыл бұрын
Can you make a video on "Maximum sum of nodes in Binary tree such that no two are adjacent" I am not able to understand this question and it was asked in the interview of my senior. So please sir a humble request from you from a subscriber please make a video on this question. It will be really helpful for students like us. Thank you for teaching...Your videos are super awsome.
@preetisaroha3118
@preetisaroha3118 5 жыл бұрын
Diameter of a tree can be calculated by only using the height function, because the diameter of a tree is nothing but maximum value of (left_height + right_height + 1) for each node. So we need to calculate this value (left_height + right_height + 1) for each node and update the result. Time complexity - O(n)
@JJ-Bond
@JJ-Bond 5 жыл бұрын
could u please show how to do this? i couldn't figure this out myself
@anig3465
@anig3465 4 жыл бұрын
NARASIMHA KARUMANCHI. THANKS FOR DETAIL EXPLANATION
@prateekkanujiya9775
@prateekkanujiya9775 5 жыл бұрын
This is brute Force . You need to go for optimal solution
@User-nq9ee
@User-nq9ee Жыл бұрын
Beautifully explained :) Thank you.
@DismalDante
@DismalDante 6 жыл бұрын
Good video. You can get a O(n) time algorithm by getting the diameter and height in the same recursive call. Just pass by reference the height in the diameter function.
@JJ-Bond
@JJ-Bond 5 жыл бұрын
can you please show how to do this? i couldn't figure it out myself...
@shreyasangane3822
@shreyasangane3822 4 жыл бұрын
Khup Sunder Explain Kelat!!! Dhanyavad
@rsKayiira
@rsKayiira 3 жыл бұрын
This code doesn't seem to work unless you write it like this. You adjust the return statements to -1 and +2 class Solution { public int height(TreeNode root) { if(root==null) return -1; else{ int left = height(root.left); int right = height(root.right); return Math.max(left,right)+1; } } public int diameterOfBinaryTree(TreeNode root) { // base case if tree is empty if (root == null) return 0; // get the height of left and right sub-trees int lh = height(root.left); int rh = height(root.right); // get the diameter of left and right sub-trees int ld = diameterOfBinaryTree(root.left); int rd = diameterOfBinaryTree(root.right); /* Return max of following three 1) Diameter of left subtree 2) Diameter of right subtree 3) Height of left subtree + height of right subtree + 1 */ return Math.max(lh + rh + 2, Math.max(ld, rd)); } }
@kmlx19
@kmlx19 4 ай бұрын
The explanation is really clear, but I have a doubt about the time complexity of this solution, it would be O(n²) or O(n)?
@vadirajjahagirdar2615
@vadirajjahagirdar2615 7 жыл бұрын
Best explanation out there. Thanks Vivekanand.
@ghostpieces2362
@ghostpieces2362 4 жыл бұрын
Could you follow-up with how do solve Leetcode 1245: Tree Diameter, which is similar to this? Thanks for the great instructional videos.
@user-zj9pq5xc7x
@user-zj9pq5xc7x 4 ай бұрын
amazing. thank you
@abhisekmandal1591
@abhisekmandal1591 5 жыл бұрын
good tutorial but this is O(n-square) solution. O(n) solution can be obtained by using height function. Code below: class Tree { /* Complete the function to get diameter of a binary tree */ int diameter(Node root) { Res r = new Res(); diameter(root,r); return r.val; } int diameter(Node root, Res res) { if(root==null) return 0; int lh = diameter(root.left,res); int rh = diameter(root.right,res); res.val = Math.max(res.val, lh+rh+1); return Math.max(lh,rh)+1; } }
@rakeshroshan829
@rakeshroshan829 5 жыл бұрын
great explanation. Thank you vivekanand fo such a good video.
@kushagrashekhawat8227
@kushagrashekhawat8227 4 жыл бұрын
You are an awesome teacher! Keep up the good work.
@yvanpearson7024
@yvanpearson7024 Жыл бұрын
In first example some people would say that diameter is 8 not 9.
@GAURAVKR1986
@GAURAVKR1986 5 жыл бұрын
Really nice explanation keep up the good work buddy!
@learntogether-growtogether865
@learntogether-growtogether865 7 жыл бұрын
Problem is very well explained ....gr8 Sir
@dhruvilprajapati4734
@dhruvilprajapati4734 Жыл бұрын
thanks for lucid explanation
@vcfirefox
@vcfirefox 2 жыл бұрын
SUPREME explanation. thanks!!
@karansachdeva8516
@karansachdeva8516 3 жыл бұрын
Great explanation
@biswaMastAadmi
@biswaMastAadmi 2 жыл бұрын
beautiful explanation
@hiteshdayaramani388
@hiteshdayaramani388 7 жыл бұрын
thank you for explaining the concept of diameter of binary tree!
@annieonee
@annieonee 3 жыл бұрын
wow best explanation so far. Thank you!
@mohdanaskhan7203
@mohdanaskhan7203 6 жыл бұрын
your videos are amazing, you just need to put them in order so that it would be easier for the viewer.
@dharanyuvi6951
@dharanyuvi6951 3 жыл бұрын
Gist: Max of ( Diameter passing through root, Max diameter not passing through root )
@shashwatagrawal8412
@shashwatagrawal8412 5 жыл бұрын
Thank you Bhaiya. Doubt cleared. 😊 Please make more videos. Very helpful.
@preetisaroha3118
@preetisaroha3118 5 жыл бұрын
Very nice explanation sir.I really appreciate your efforts.Thanks.
@prashantnagrurkar2784
@prashantnagrurkar2784 4 жыл бұрын
Thanks a lot! 😊 A very good explanation 👌 Perfect speed for me
@mchandresh
@mchandresh 7 жыл бұрын
you make things so simple bro. thank you for sharing. I am fan of you. could you please sometime post video on eigen value and eigen vectors
@vicky888
@vicky888 3 жыл бұрын
Great video!!!
@saivigneshrajendran867
@saivigneshrajendran867 7 жыл бұрын
I am a very big fan of you bro.. plz make more videos.. and my humble request to you is that it will very much helpful if you consider some java while explain the code... Thanks from coimbatore.
@pratapkumarchandra6488
@pratapkumarchandra6488 4 жыл бұрын
this is the best explanation i was looking for u. thank u for making it so simple :)
@darod6098
@darod6098 4 жыл бұрын
I only see this video and subscribed. Just EXCELLENT.
@chetanjain5097
@chetanjain5097 2 жыл бұрын
Could you please post code as well so that we can copy parts of it and test it out ourselves?
@parthshah6343
@parthshah6343 4 жыл бұрын
Superb explanation!
@griffinbaker9792
@griffinbaker9792 2 жыл бұрын
The time complexity of this algo is O(N^2) right? Because we have to calculate the height as well as the diameter for each given node, and for both we need to make recursive calls down the tree.
@pranavbhat92
@pranavbhat92 8 ай бұрын
Also, where is the height function here? I was looking for the same comment
@abhisheka2p2
@abhisheka2p2 6 жыл бұрын
You're great! Hope u get many likes and subs.
@alfredoluco189
@alfredoluco189 3 жыл бұрын
Great video and great explanation. Thanks a lot!
@DeviDevi-yr2sv
@DeviDevi-yr2sv 3 жыл бұрын
Great explaination
@rakeshroshan829
@rakeshroshan829 5 жыл бұрын
can u please make a video on RED-BLACK Tree
@TheSridharraj
@TheSridharraj 3 жыл бұрын
Complexity is O(n^2) right?
@abhishekjain7173
@abhishekjain7173 6 жыл бұрын
Very nice explanation !
@kasyapdharanikota8570
@kasyapdharanikota8570 3 жыл бұрын
very well explained
@Amanyadav-ec3hn
@Amanyadav-ec3hn 4 жыл бұрын
Thanks for the video. Also, try to explain the time complexity of the solution.
@yanlingyang256
@yanlingyang256 7 жыл бұрын
perfect!!!!!!!! perfect explanation!!!!!!!!!!! Thanks :)
@RiteshSingh-op3jd
@RiteshSingh-op3jd 7 жыл бұрын
I am very big fan of yours. Please keep up the good work.
@yvanpearson7024
@yvanpearson7024 Жыл бұрын
this is a O(N^2) solution, i would only study O(N) solutions
@georgebrooking3820
@georgebrooking3820 3 жыл бұрын
YOU ARE A HERO!!!!!!!
@ShivangiSingh-wc3gk
@ShivangiSingh-wc3gk 6 жыл бұрын
Dear Professor, Please can you make a video on how to find the maximum width of a binary tree. Thank You
@agyatanonymous3995
@agyatanonymous3995 6 жыл бұрын
level order traversal might be the answer for this
@alishagarg150
@alishagarg150 4 жыл бұрын
Sir there is a problem with this explanation.In case of an AVL tree where the diameter is supposed to be zero,this gives out some other ans.Kindly check on that!!
@Adityasharma-oe8zp
@Adityasharma-oe8zp 3 жыл бұрын
He is god of algorithms....❤️❤️
@coderajput1816
@coderajput1816 7 жыл бұрын
your explanation is good but i think u should use stack also to run each steps thank u 4 this video
@a7medk7alid7
@a7medk7alid7 Жыл бұрын
C++ code class Solution { public: int diameterOfBinaryTree(TreeNode* root) { if (!root) return 0; int lheight = height(root->left); int rheight = height(root->right); int ldiameter = diameterOfBinaryTree(root->left); int rdiameter = diameterOfBinaryTree(root->right); return max((lheight + rheight), max(ldiameter, rdiameter)); } int height(TreeNode* root){ if (!root) return 0; int lheight = height(root->left); int rheight = height(root->right); if (lheight > rheight) return(lheight+1); return rheight+1; } };
@reviewsonly4894
@reviewsonly4894 Жыл бұрын
thanks bri im a iitian very beginnner in coding thanks
@azad1300
@azad1300 4 жыл бұрын
While calculating diameter , why are not doing +1 ? if so will the diameter value get increment ?
@remyb9937
@remyb9937 6 жыл бұрын
Excellent explanation
@animemaker7433
@animemaker7433 6 жыл бұрын
why did u stop making videos??? You are damn good man
@sivaganesh4489
@sivaganesh4489 4 жыл бұрын
yes
@swagatpatra2139
@swagatpatra2139 4 жыл бұрын
int maxDia; int diameter(TreeNode root) { diaHelper(root); return maxDia; } int diaHelper(TreeNode root){ if(root == null) return 0; int left = diaHelper(root.left); int right = diaHelper(root.right); maxDia = Math.max(maxDia, left + right+1); return Math.max(left,right)+1; }
@johngerassimou8898
@johngerassimou8898 9 ай бұрын
Very good! Thank you sir.
@tonyz2203
@tonyz2203 4 жыл бұрын
Good explanation, thank you!
@anamikaahmed4887
@anamikaahmed4887 4 жыл бұрын
Well explained! Thank you for this!
@jegatheeshm93
@jegatheeshm93 4 жыл бұрын
Good Explanation.
@one_percent_up
@one_percent_up 4 жыл бұрын
Just to the understading way to the concepts
@veerrajuyeleti8541
@veerrajuyeleti8541 6 жыл бұрын
sir can u do a video on find the largest bst(binary search tree) in a binary tree .
@jeezradz
@jeezradz 4 жыл бұрын
what is the TIME COMPLEXITY for this?
@TheBreyHD
@TheBreyHD 4 жыл бұрын
O(n^2)
@TianmenDream
@TianmenDream 5 жыл бұрын
What's the time complexity of your proposed solution? Looks like quite hard to analyze.
@bonkers4490
@bonkers4490 5 жыл бұрын
Time complexity is O(2n) i.e O(n) where n is the number of nodes in the tree. In all the recursive calls, you find the height of left and right subtree by visiting each node at most once. Then you find the diameter of left subtree and right subtree considering root as any node in tree except the root of original tree, and this makes you visit n nodes again. Therefore, 2n which is none other than O(n).
@GauravKawatrakir
@GauravKawatrakir 3 жыл бұрын
This solution takes O(n2) "n square".
@retrogame3138
@retrogame3138 4 жыл бұрын
why you stopped to upload new videos
@shrad6611
@shrad6611 5 жыл бұрын
Is I am the only one who give reply of his hello when in good mood :) hahaha lol
@sameedyousuf6036
@sameedyousuf6036 4 жыл бұрын
lol i said okay every time he said "okay?"
@goldent4655
@goldent4655 3 жыл бұрын
What's the time and space complexity?
@niharikapatil902
@niharikapatil902 4 жыл бұрын
You are soooo gooooddd at this
@dileepmatha8076
@dileepmatha8076 7 жыл бұрын
how to find sum of nodes of a diameter ????
@Atpugtihsrah
@Atpugtihsrah 6 жыл бұрын
Can you explain the O(n) solution?
@piyushchaudhari397
@piyushchaudhari397 4 жыл бұрын
Great work !
@PradeepKumar-so5wq
@PradeepKumar-so5wq 5 жыл бұрын
nice explaination man keep posting .post some greedy method videos
@MrAvtar1
@MrAvtar1 6 жыл бұрын
What is the time complexity of this approach?
@Ashish.Shukla9
@Ashish.Shukla9 5 жыл бұрын
O (n^2)
@piotropyd9806
@piotropyd9806 6 жыл бұрын
great explanation !
@basavarajpatil9821
@basavarajpatil9821 3 жыл бұрын
code for O(n) time complexity
Check if two binary trees are Isomorphic
14:12
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 20 М.
Height of a Binary Tree / Maximum depth of a binary tree Algorithm [REVISITED]
16:50
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 119 М.
Hoodie gets wicked makeover! 😲
00:47
Justin Flom
Рет қаралды 133 МЛН
The Singing Challenge #joker #Harriet Quinn
00:35
佐助与鸣人
Рет қаралды 44 МЛН
За кого болели?😂
00:18
МЯТНАЯ ФАНТА
Рет қаралды 3 МЛН
If people acted like cats 🙀😹 LeoNata family #shorts
00:22
LeoNata Family
Рет қаралды 9 МЛН
Diameter of a binary tree | Leetcode #543
13:31
Techdose
Рет қаралды 61 М.
Boundary traversal of binary tree (Border Elements)
18:20
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 26 М.
48 Diameter of a Binary Tree
15:13
Aditya Verma
Рет қаралды 128 М.
How Many Marbles Does it Take to Charge My Phone?
18:06
Engineezy
Рет қаралды 116 М.
Maximum Sum SubArray (Kadane's algorithm) (Largest Sum Contigous SubArray)
17:30
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 92 М.
Print diagonal elements in binary tree(code/Algorithm/Program)
25:19
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 20 М.
Number of Binary Search Trees possible with 'n' nodes(KEYS)
29:21
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 23 М.
L16. Diameter of Binary Tree | C++ | Java
13:47
take U forward
Рет қаралды 378 М.
Hoodie gets wicked makeover! 😲
00:47
Justin Flom
Рет қаралды 133 МЛН