Diameter of a Binary Tree (Code/ Algorithm)

Поділитися
Вставка
  • Опубліковано 19 вер 2024
  • Find the diameter of a binary tree. The number of nodes on the longest path in a binary tree is the diameter. This is a recursive code.
    Height of a binary Tree video :- • Height of a Binary Tre...

КОМЕНТАРІ • 183

  • @irynasherepot9882
    @irynasherepot9882 5 років тому +74

    This is a great video, perfect speed for someone new and with English second language. Thank you for making it so easy to understand!

  • @praveenchouhan6388
    @praveenchouhan6388 4 роки тому +9

    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.

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

    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 11 місяців тому

      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.

  • @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

  • @Adityasharma-oe8zp
    @Adityasharma-oe8zp 3 роки тому +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

  • @jeezradz
    @jeezradz 4 роки тому +5

    just wow! I was struggling so much and you made this crystal clear. Thankyou! Great video~!

  • @pahehepaa4182
    @pahehepaa4182 4 роки тому +1

    Very good explanation! The other guys were confusing until I stumbled upon this guy's video.

  • @ABU_BEKIR_SIDDIK
    @ABU_BEKIR_SIDDIK 6 років тому +128

    Just play this video 1.5 speed.

    • @agyatanonymous3995
      @agyatanonymous3995 5 років тому +14

      2x works as just perfectly!

    • @humblecoder9119
      @humblecoder9119 5 років тому +10

      LOL ! But, he is a great teacher and doing awesome job ! Thank you !

    • @ishan_kumar
      @ishan_kumar 5 років тому +9

      I wish there is 3X option.

    • @sandeepvedavyas8701
      @sandeepvedavyas8701 4 роки тому +8

      @@ishan_kumar press ctrl + shift + j. In the console window type
      document.getElementsByTagName("video")[0].playbackRate = 3.0

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

      @@ishan_kumar U can also add video speed controller extension

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

    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 2 роки тому

      True, with the video from the same problem description for the height would be confusing.

  • @AbhiKumar-yk9sr
    @AbhiKumar-yk9sr Рік тому

    Sir Your explanation is nice , every person can easily understand

  • @jacktrainer4387
    @jacktrainer4387 4 роки тому +1

    Most thorough explanation out there! Great job!

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

    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);
    }

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

    Vivek, that is a great video. Great explanation that is very much personalized for everyone. Thank you!

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

    You are blessed with teaching. I wish I had found this video earlier.

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

    Thanks sir, I was just forgetting the 2nd case when diameter is not passing through the root. Not I got it. Thanks

  • @mchandresh
    @mchandresh 7 років тому +6

    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

  • @shrad6611
    @shrad6611 5 років тому +6

    Is I am the only one who give reply of his hello when in good mood :) hahaha lol

  • @ChandraShekhar-by3cd
    @ChandraShekhar-by3cd 4 роки тому

    You Explain like a PRO..Thanks for such a detailed explanation!

  • @ytuser659
    @ytuser659 4 роки тому +1

    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 .

  • @saivigneshrajendran867
    @saivigneshrajendran867 7 років тому +3

    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.

  • @rakeshroshan829
    @rakeshroshan829 5 років тому +2

    great explanation. Thank you vivekanand fo such a good video.

  • @learntogether-growtogether865
    @learntogether-growtogether865 7 років тому +2

    Problem is very well explained ....gr8 Sir

  • @DismalDante
    @DismalDante 6 років тому +3

    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 років тому +1

      can you please show how to do this? i couldn't figure it out myself...

  • @kushagrashekhawat8227
    @kushagrashekhawat8227 4 роки тому +1

    You are an awesome teacher! Keep up the good work.

  • @thelasttimeitookashowerwas7069
    @thelasttimeitookashowerwas7069 4 роки тому +22

    finding a recursive solution is extremely tough ):

    • @nivedithat4745
      @nivedithat4745 4 роки тому +9

      I kinda like how creative your username is😂... Made my day😂😂

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

      Hmm it is difficult to find recursive one

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

    Thank youu. I was really struggling to understand this and you explained it beautifully

  • @abhisheka2p2
    @abhisheka2p2 6 років тому +2

    You're great! Hope u get many likes and subs.

  • @yanlingyang256
    @yanlingyang256 6 років тому +7

    perfect!!!!!!!! perfect explanation!!!!!!!!!!! Thanks :)

  • @User-nq9ee
    @User-nq9ee 11 місяців тому

    Beautifully explained :) Thank you.

  • @GAURAVKR1986
    @GAURAVKR1986 5 років тому +1

    Really nice explanation keep up the good work buddy!

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

    Best Explaination so far. Thankyou sir

  • @mohdanaskhan7203
    @mohdanaskhan7203 6 років тому +3

    your videos are amazing, you just need to put them in order so that it would be easier for the viewer.

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

    Could you follow-up with how do solve Leetcode 1245: Tree Diameter, which is similar to this? Thanks for the great instructional videos.

  • @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.

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

    Great video!!!

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

    Thanks a lot! 😊
    A very good explanation 👌
    Perfect speed for me

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

    thanks for lucid explanation

  • @shreyasangane3822
    @shreyasangane3822 4 роки тому

    Khup Sunder Explain Kelat!!! Dhanyavad

  • @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.

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

    beautiful explanation

  • @vadirajjahagirdar2615
    @vadirajjahagirdar2615 7 років тому

    Best explanation out there. Thanks Vivekanand.

  • @hiteshdayaramani388
    @hiteshdayaramani388 7 років тому

    thank you for explaining the concept of diameter of binary tree!

  • @anig3465
    @anig3465 4 роки тому

    NARASIMHA KARUMANCHI. THANKS FOR DETAIL EXPLANATION

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

    Great explanation

  • @preetisaroha3118
    @preetisaroha3118 5 років тому +3

    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 років тому +1

      could u please show how to do this? i couldn't figure this out myself

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

    SUPREME explanation. thanks!!

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

    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)?

  • @preetisaroha3118
    @preetisaroha3118 5 років тому

    Very nice explanation sir.I really appreciate your efforts.Thanks.

  • @pratapkumarchandra6488
    @pratapkumarchandra6488 4 роки тому

    this is the best explanation i was looking for u. thank u for making it so simple :)

  • @DeviDevi-yr2sv
    @DeviDevi-yr2sv 3 роки тому

    Great explaination

  • @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 6 місяців тому

      Also, where is the height function here? I was looking for the same comment

  • @shashwatagrawal8412
    @shashwatagrawal8412 5 років тому

    Thank you Bhaiya. Doubt cleared. 😊
    Please make more videos. Very helpful.

  • @darod6098
    @darod6098 4 роки тому

    I only see this video and subscribed. Just EXCELLENT.

  • @RiteshSingh-op3jd
    @RiteshSingh-op3jd 7 років тому

    I am very big fan of yours. Please keep up the good work.

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

    Great video and great explanation. Thanks a lot!

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

    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));
    }
    }

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

    very well explained

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

    wow best explanation so far. Thank you!

  • @abhishekjain7173
    @abhishekjain7173 6 років тому

    Very nice explanation !

  • @parthshah6343
    @parthshah6343 4 роки тому

    Superb explanation!

  • @anamikaahmed4887
    @anamikaahmed4887 4 роки тому

    Well explained! Thank you for this!

  • @prateekkanujiya9775
    @prateekkanujiya9775 5 років тому +5

    This is brute Force . You need to go for optimal solution

  • @remyb9937
    @remyb9937 6 років тому

    Excellent explanation

  • @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;
    }
    }

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

    Very good! Thank you sir.

  • @niharikapatil902
    @niharikapatil902 4 роки тому

    You are soooo gooooddd at this

  • @karangupta6402
    @karangupta6402 5 років тому +2

    Just one word "Awesome" :)

  • @coderajput1816
    @coderajput1816 7 років тому

    your explanation is good but i think u should use stack also to run each steps
    thank u 4 this video

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

    great explanation!

  • @tonyz2203
    @tonyz2203 4 роки тому

    Good explanation, thank you!

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

    YOU ARE A HERO!!!!!!!

  • @PradeepKumar-so5wq
    @PradeepKumar-so5wq 5 років тому

    nice explaination man keep posting .post some greedy method videos

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

    In first example some people would say that diameter is 8 not 9.

  • @jegatheeshm93
    @jegatheeshm93 4 роки тому

    Good Explanation.

  • @piyushchaudhari397
    @piyushchaudhari397 4 роки тому

    Great work !

  • @ShivangiSingh-wc3gk
    @ShivangiSingh-wc3gk 6 років тому +2

    Dear Professor,
    Please can you make a video on how to find the maximum width of a binary tree.
    Thank You

    • @agyatanonymous3995
      @agyatanonymous3995 5 років тому +5

      level order traversal might be the answer for this

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

    Can someone please help me understand the concept of length of the path. I mean in this problem what sir is explaining is it assumed that length of path = number of nodes on the path OR is length of path = is represented by the number of edges between them? since this could change the way we implement right?anyone?

  • @Amanyadav-ec3hn
    @Amanyadav-ec3hn 4 роки тому

    Thanks for the video. Also, try to explain the time complexity of the solution.

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

    this is a O(N^2) solution, i would only study O(N) solutions

  • @tapanjeetroy8266
    @tapanjeetroy8266 5 років тому

    Thanks a lot for making us understand

  • @bhupalibaishya2136
    @bhupalibaishya2136 6 років тому +1

    sir, in the very first tree, lheight will b 2 n rheight=4 then lheight+right+1= 7 whereas answer should be 9 ...I am confused .pls explain

    • @akashnigam010
      @akashnigam010 5 років тому

      lHeight = 3 and rHeight = 5.
      lHeight + rHeight + 1 = 3 + 5 + 1 = 9
      Height of a tree = number of edges between the root and the farthest leaf

  • @user-zj9pq5xc7x
    @user-zj9pq5xc7x 2 місяці тому

    amazing. thank you

  • @animemaker7433
    @animemaker7433 5 років тому +6

    why did u stop making videos??? You are damn good man

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

    Could you please post code as well so that we can copy parts of it and test it out ourselves?

  • @jeezradz
    @jeezradz 4 роки тому +1

    what is the TIME COMPLEXITY for this?

  • @rrsonia10
    @rrsonia10 4 роки тому

    this was awesome! thank you!

  • @azad1300
    @azad1300 4 роки тому

    While calculating diameter , why are not doing +1 ?
    if so will the diameter value get increment ?

  • @rakeshroshan829
    @rakeshroshan829 5 років тому +1

    can u please make a video on RED-BLACK Tree

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

    Gist:
    Max of ( Diameter passing through root, Max diameter not passing through root )

  • @Mei-ir3ml
    @Mei-ir3ml 4 роки тому

    You are really great!

  • @shettyanvita
    @shettyanvita 5 років тому

    thank you for the explanation

  • @lucaandolfi4558
    @lucaandolfi4558 6 років тому

    Very clear, thanks

  • @aanchalsharma5264
    @aanchalsharma5264 4 роки тому

    Best vedio

  • @donl9027
    @donl9027 18 днів тому

    The definition of the diameter in this video is wrong. Should be Diameter = number of nodes on the longest path - 1

  • @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).

  • @Adityasharma-oe8zp
    @Adityasharma-oe8zp 3 роки тому

    He is god of algorithms....❤️❤️

  • @jeshocarmel
    @jeshocarmel 4 роки тому

    Excellent !

  • @abhro5992
    @abhro5992 6 років тому

    very helpful! Thanks

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

    Complexity is O(n^2) right?