Skip to main content

Find the sum of longest path from root to leaf node

Given a binary tree, Our goal is to get the sum of longest path in this tree.

Example
/* Binary Tree
-----------------------
        1
     /    \
    2      5
   / \    /  \
  1   7  7    2
     /    \    \
    9      1   -3
          / 
        -7 
*/
/* First Path
-----------------------
      1
     / 
    2 
   /
  1 

    Length : 3
    Sum    : 4
*/

/* Second Path
-----------------------
      1
     /  
    2 
     \ 
      7
     / 
    9

    Length : 4
    Sum    : 19    
*/

/* Third Path
-----------------------
        1
         \
          5
         /  
        7  
         \  
          1 
         / 
       -7 

    Length : 5
    Sum    : 7  
*/


/* Fourth Path
-----------------------
        1
         \
          5
           \
            2
             \
             -3


    Length : 4
    Sum    : 5          
*/

Output :  7
[Because path 3 are length is higher to other]

If in case more than one path contains same resultant length then in this situation we accept sum of first (first path). Here given code implementation process.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment