Binary tree maximum path sum | Leetcode

Поділитися
Вставка
  • Опубліковано 26 вер 2024
  • This video explains a very important interview programming question which is to find the maximum path sum in a binary tree. This is a very important binary tree question and the problem is very similar to finding diameter of a binary tree. I have explained the intuition for solving this problem including all the cases to be handled. I have explained the code flow with proper examples and code explanation is present at the end of the video.As usual, CODE LINK is present in the description below. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
    CODE LINK: gist.github.co...
    Similar Problem:
    Diameter of a binary tree: • Diameter of a binary t...

КОМЕНТАРІ • 206

  • @shubhiagarwal4047
    @shubhiagarwal4047 3 роки тому +12

    Sir , this explanation deserves much more applaud , that's why I shared your channel to all my juniors.

  • @yimingzhao3753
    @yimingzhao3753 4 роки тому +23

    Seen a few explanations on UA-cam, this is the best one so far, way to go!

  • @uwontlikeit
    @uwontlikeit 4 роки тому +24

    1:09 - EXAMPLE 2 IS INCORRECT. max sum = 6 (not 5) and includes the root, and the rightest node

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

    Well explained with example 🍁 , Smart way by using the three cases it clear all my doubts 👍🏻.

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

      Thanks man :)

    • @ssss-jd9cl
      @ssss-jd9cl 2 роки тому

      can anyone explain why m21 has taken value max of ms and left+right+root->data. we can take only some value of left+right+node also. I am getting confused in this. Anyone explain.

  • @saharshrathi7828
    @saharshrathi7828 4 роки тому +4

    Such a great explanation! I just watched the video to understand the algorithm and you explained it so good! Then coded the algorithm by myself and the solution got accepted in the first try! Subscribed.

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

    The example which you have illustrated where the sum was 5, the maximum sum we can achieve is 3->2->(-1) ->2 sum=6

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

    Probably the best explanation of this problem on You Tube .. Thanks Man

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

    Really good explanation. I started to understand the logic when with a playback speed of .75. Thanks

  • @lemax2980
    @lemax2980 4 роки тому +6

    Respect for the effort! 🙃.
    Thank you for the great content and please , if you are comfortable,teach us about graphs after the leetcode saga😅

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

    This is the best explanation I have come across for this question.

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

    he saves results as max which would o/p the max sum
    but doest return the result since the left or right side of the tress must be a straight iine and not a sub tree

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

    Nice! The only explanation I understood on UA-cam :-)

  • @m.praneethreddy7335
    @m.praneethreddy7335 4 роки тому

    Best channel in the youtube for data structures and algorithms👌👌

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

    The way in which you explained this complex problem is lit💥
    Keep it up👍

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

    Nice explanation!! The solution felt really intuitive after looking at this video

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

    No one Can Explain Like You .

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

    worlds best video ,sir aur bnayo aisi interview bit se lekr ,clear all the doubts

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

    Great Video, best explanation available. To me the tricky part was to understand why m21 needs to be a max(ms, left + right + root->val) and not just: left + right + root->val. Could you maybe elaborate on that. Thank you!

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

      Thanks. Because there might be a max sum path in either left or right subtree which is not rooted at current node.

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

    Damn!! It was leetcode HARD I understood at one go. Kudos to you ! You provide quality content. Keep making videos and thank you so much.

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

    Can you explain why only case 1 is returned, only that part is confusing me.

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

    By far the best explanation

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

    @Techdose just one doubt i had why we are returning case 1 value only and hence returning max_straight .Please give clear explaination.

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

    Very good explanation of the Cases. Thank You !

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

    Sir ,could u please provide the link for inserting nodes into binary tree dynamically at what ever place we want,
    But in generally I found inserting via level order in binary tree.

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

    at 1.46 in the second tree example why u havent consider -1 , 2 in ur path ?? the maxsum will be 6 which is greater than 5 as in ur selected path

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

      Yes you are correct. Actually I wanted it to be -2 but it turned out to be 2. My bad. Consider that -2.

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

      @@techdose4u okay sir thanks

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

      Thanks for pointing out :)

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

      @@techdose4u one doubt sir...I also solve problems in C++ ...and I wanted to ask what those code statements at line 29,30 mean ?...

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

    Supppppppperrrrbbbbb explanation....U just made a hard problem look so easier . Explanation is awesome :)

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

    Excellent explanation! I understood this in the first go. I'm now curious to know, since every recursive approach also has an iterative approach, how will this problem be solved iteratively, without recursion? Also, since we've kept track of the max sum, can we also extend this problem to return a list of nodes which are part of max sum path? Like in the above example, max sum = 18, nodes = [8->4->1->5]

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

    Thank you for showing/explaining the algorithm before the code. I use javascript and so it is helpful.

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

    Please make video on path sum question where we have to check if path with given sum exists on leet code

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

      Maybe I will take this when I do TREE.

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

    thank you, this was the best explanation I could find.

  • @Neerajkumar-xl9kx
    @Neerajkumar-xl9kx 4 роки тому +1

    can't be explained better than this...thank you

  • @aadhavan-arunkumar
    @aadhavan-arunkumar 3 роки тому +1

    Amazing explanation!. Do you mind sharing where do you work?

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

      Currently I am teaching students and working professionals and guiding them to get better opportunities :) Follow me on LinkedIn to know more

  • @LaxmiNarayana-zs5vz
    @LaxmiNarayana-zs5vz 4 роки тому +2

    Thanks for the great explanation!.
    how to actually store the path and print the nodes involved in our maximum path?

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

    I was able to do it by your bt diameter ques. Explanation.
    Thank you 😀

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

    Why is it traversing to every node 3 times? It looks like the traversal just visits each node once.

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

      Going to child and then coming back and again going to another child. It's technically 1 visit but recursion makes it 3 times if you consider going from child to parent as a visite :)

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

    Why are we returning the case1 value at the end instead of the result?

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

    very good explanation for a hard problem

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

    Best explanation so far!

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

    very nicely explained in detailed.

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

    Why do we return case 1 in the helper function?

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

    Amazing Explanation Sir, Looking forward to more hard questions like these!

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

      They will come in may challenge :)

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

    excellent explanation ! keep going !

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

    i searched tons of resource but couldn't understand this problem, thank you so much sir for this video :)

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

    So beautiful, I done it the hard way it got AC anyway, I was unsure of what to return to the parent LOL

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

    I liked your solution on diameter of a trees, and it seemed to me jus same question with one difference that here there were negative values. Just because I was familiar with that approach used that
    class Solution {
    public int maxPathSum(TreeNode root) {
    return maxPathSumRec(root)[1];
    }
    int[] maxPathSumRec(TreeNode root){
    int largestSum = -99999;
    if(root == null){
    return new int[]{0,largestSum};
    }
    int[] left = maxPathSumRec(root.left);
    int[] right = maxPathSumRec(root.right);
    left[0] = Math.max(left[0], 0);
    right[0] = Math.max(right[0], 0);
    largestSum = Math.max((left[0] + right[0] + root.val), Math.max(left[1],right[1]));
    return new int[]{Math.max(left[0],right[0])+root.val,largestSum};
    }
    }

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

    This is a really nice explanation! Thank you!

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

    Very nice explanation

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

    Well done!!Explanation is very nice.

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

    This is a hard problem to understand but sir you made it easy❤️

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

      👍🏼

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

      @@techdose4u sir can we have a video on🙏 print all ''k"" sum paths in a Binary tree🙏

  • @RajatSingh-dg8ov
    @RajatSingh-dg8ov 3 роки тому

    why can we only return max straight value?. You did not explain that. If there's no use of doing maxCaseVal and result, since they are not getting returned, even max_straight is not even updated anywhere after line 21. Why not return that directly?.

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

    Best explanation , I have ever seen ;)

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

    Amazing explanation!!

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

    Nice Explanation........Nice to see having no Dislikes.

  • @InderjeetSingh-no3pp
    @InderjeetSingh-no3pp 4 роки тому +1

    Nice explanation.....easily understandable

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

    You explain really nice and simple !!

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

    Hey, please make a video on sum of distances in a tree question from leetcode .

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

    How to come up with this solution in interview if we have not seen this problem before?

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

      You must have seen this problem. This is one the most common tree problem. There can be multiple variations of this. If you have solved only 1 of them then you can get the idea.

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

      @@techdose4u I learnt this the hard way. Thanks for the awesome video

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

    Why are we returning max-straight? why we can't we return result. I didn't get this

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

    Sir in
    112. Path Sum(Leetcode problem)
    Sir consider one case when my sum is lesser than the zero (after reaches of some node).
    and however we know my solution is not in this sub tree, i am simply continuing recursion tiil i reaches leaf node.
    sir is there any solution to this .......
    [5,4,8,11,null,13,4,7,2,null,null,null,1,3,4]
    sum == 22
    here after i reaches the node 7 , here i get know this is not the best path,however i am continuing recursion of leaf node 3 and 4
    sir if i break the recursion at node 7 we can reduce time complexity am i right sir......

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

    Excellently explained!!

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

    very well explained.. Thanks

  • @OGIL-ir3rp
    @OGIL-ir3rp 3 роки тому +1

    **** JAVA VERSION OF THE ABOVE APPROACH ******
    class MyInt {
    int result = Integer.MIN_VALUE;
    }
    public int maxPathSum(TreeNode root) {
    MyInt myint = new MyInt();
    maxPathSumHelper( root, myint );
    return myint.result;
    }
    public int maxPathSumHelper(TreeNode root, MyInt myint){
    if( root == null ) return 0;
    int leftSum = maxPathSumHelper( root.left, myint );
    int rightSum = maxPathSumHelper( root.right, myint );
    int maximumSum = Math.max( Math.max( leftSum, rightSum) + root.val, root.val );
    int maxSumAcross = Math.max( maximumSum, leftSum + root.val + rightSum );
    myint.result = Math.max( maxSumAcross, myint.result );
    return maximumSum;
    }

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

    great explanation

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

    Java Code Hope it helps!
    class Solution {
    static int result=Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root)
    {
    if(root==null) return 0;
    Max_finder(root);
    return result;
    }
    private static int Max_finder(TreeNode root)
    {
    if(root==null) return 0;
    //going down to leaf node and will start calculating from there.
    int left=Max_finder(root.left);
    int right=Max_finder(root.right);
    // calculating while backtracking.
    int Straight_path=Math.max(Math.max(left,right)+root.val,root.val);
    int all_Maxval=Math.max(Straight_path,left+right+root.val);
    result=Math.max(all_Maxval,result);
    return Straight_path;
    }
    }

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

    Java Solution
    -----------------------
    class Solution {
    int sum=Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
    if(root==null)
    return 0;
    height(root);
    return sum;
    }
    public int height(TreeNode root){
    if(root==null)
    return 0;
    int leftS=height(root.left);
    int rightS=height(root.right);
    int ms=Math.max(Math.max(leftS,rightS)+root.val,root.val);
    int ms12=Math.max(ms,root.val+leftS+rightS);
    sum=Math.max(sum,ms12);
    return ms;
    }
    }

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

    Great Explaination Sir

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

    Why we are return max_ straight instead of result.🤔🤔🤔

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

    Amazing explanation 👌

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

    bhai aap legend ho yaar

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

    Same solution in java:
    public class BinaryTreeMaxPathSum {
    int max_seen_until_now=Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
    maxPath(root);
    return max_seen_until_now;
    }
    public int maxPath(TreeNode root) {
    if(root==null){
    return 0;
    }
    int left=maxPath(root.left);
    int right=maxPath(root.right);
    int max_straight_path=Math.max(Math.max(left,right)+root.val,root.val);
    int max_curr_node_as_root=Math.max(max_straight_path,left+right+root.val);
    max_seen_until_now=Math.max(max_curr_node_as_root,max_seen_until_now);
    return max_straight_path;
    }

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

    Amazing explanation! Thanks a lot

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

    very well explained, thanks!

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

    Why you returning max_straight in recursion function.

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

      I got it bcz we want left and right value of curr node that's why returning max_straight

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

    These are also such questions to prepare for. Interviews

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

    outstanding solution brother

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

    Can you please mention TC and SC for this approach??

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

    how much time and practice needs to solve problems like this?
    n how to do?

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

    java implementation not passing all test cases on leetcode

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

    for input -9 6 -10 output is 6 but expected output is -13 in gfg

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

    Thank you very much Mate. Very nice explanation

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

    Thanks!

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

    In 2nd example stating at 1:00 minute, the maximum path of the tree should be 6 and not 5. The max path still goes through the root. It goes like- 3->2->-1->2 :)

  • @RahulKumar-wv4ti
    @RahulKumar-wv4ti 3 роки тому +1

    Thanks bro

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

    brilliant explanation.. thanks alot.. :)

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

    Wonderful

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

    ok this explanation is pretty damn clear

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

    Thanks a lot.!!

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

    python solution
    class Solution:
    def maxPathSum(self, root) :
    self.ans = -float('inf')
    def traverse_path(root):
    if not root:
    return 0
    left = max(traverse_path(root.left),0)
    right = max(traverse_path(root.right),0)
    val = root.val
    self.ans = max(self.ans,val+left+right)
    return val+max(left,right)
    traverse_path(root)
    return self.ans

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

    why we returning max_s instead result???

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

      I have explained this clearly. We are returning MS (case-1) value only because result is keeping track of max path sum found so far. It may or may not include the current node. Also, result is passed by reference and hence latest changes are available at places. No need to return result. The only thing we want to return is MS because we want to check if we can find some other path which will have more path sum as compared to current maximum stored in result.

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

      got the solution keep uploading more videos it help our coding skills

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

    Thanks bhai

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

    Here's mine
    int maxi(int a, int b, int c){
    return max(max(a, b), c);// max of 3 no(s)
    }
    int helper(TreeNode* root){
    // if at leaf check if positive and add
    if(!root->left && !root->right)return max(root->val, 0);
    int left = INT_MIN;
    int right = INT_MIN;
    if(root->left)left = helper(root->left); // should left side be chosen ?
    if(root->right)right = helper(root->right); // should right side be chosen ?
    return max(max(left, right) + root->val, 0); // max of both side + the value is > 0 or not ?
    }
    int cross(TreeNode* root){
    int x = 0, y = 0;
    if(root->right) x = helper(root->right); // should right side be added or not ?
    if(root->left) y = helper(root->left); // should left side be added or not ?
    return root-> val + x + y; // path through root (sum)
    }
    int maxPathSum(TreeNode* root) {
    // if single node return it
    if(!root->left && !root->right)return root->val;
    int left = INT_MIN; // max path sum (completely left side)
    int right = INT_MIN; // max path sum (completely right side)
    if(root->left)left = maxPathSum(root->left);
    if(root->right)right = maxPathSum(root->right);
    int through = cross(root); // max path sum passing necessary through root
    return maxi(left, right, through); // max of all is the ans
    }

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

      Looks messy 😅

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

      @@techdose4u yeah youtube doesn't support code yet ig

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

    Excellent!

  • @evgeni-nabokov
    @evgeni-nabokov 4 роки тому +1

    The solution is overcomplicated. The problem similar to the problem of the diameter of the binary tree. Just a little change in formula for left and right values. In this case, we have to compare left and right values to 0 to disregard negative sums of branches.

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

      You can directly copy the the code of diamter of a binary tree by just changing the objective and it will work. I dint think this was complicated 😅 If you compare only left and right then what about case 3 values? How will you handle that?

    • @evgeni-nabokov
      @evgeni-nabokov 4 роки тому

      @@techdose4u There is only one case -- the node is the root of the path. The path can be a single node, the path can be a root node with a single branch, or regular path.

    • @evgeni-nabokov
      @evgeni-nabokov 4 роки тому

      @@techdose4u gist.github.com/evgeni-nabokov/d67d098aea95e48e20bb0c219983257d

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

    not working in java. passes 29/93 cases

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

      There must be some logical error or some minor implementation glitch with your java code. Please review and compare carefully.

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

    Thank you!

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

    Sir please help me i m math teacher in school i want to make online video on youtube please tell me which digital board you use sir please sir

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

    good explanation sir

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

    0.43 example 2 : Max sum is 6 not 5.

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

    super hard to come up in the interview

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

    @14:05, the Result is returned, but int the code, why can you only return max_straight and not the result?

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

      Yes , even I have the same question , 18 is stored in result and if we return ms don't we get 12 instead??