Program to find sum of longest sum path from root to leaf of a binary tree in Python


Suppose we have a binary tree, we have to find the sum of the longest path from the root to a leaf node. If there are two same long paths, return the path with larger sum.

So, if the input is like

then the output will be 20.

To solve this, we will follow these steps −

  • Define a function rec() . This will take curr

  • if curr is null, then

    • return(0, 0)

  • bigger := maximum of rec(left of curr) , rec(right of curr)

  • return a pair (bigger[0] + 1, bigger[1] + value of curr)

  • From the main method do the following −

  • ret := rec(root)

  • return the 1th index of ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

class TreeNode:
   def __init__(self, val, left=None, right=None):
      self.val = val
      self.left = left
      self.right = right

class Solution:
   def solve(self, root):
      def rec(curr):
         if not curr:
            return (0, 0)
         bigger = max(rec(curr.left), rec(curr.right))
         return (bigger[0] + 1, bigger[1] + curr.val)
      return rec(root)[1]
ob = Solution()
root = TreeNode(2)
root.left = TreeNode(10)
root.right = TreeNode(4)
root.right.left = TreeNode(8)
root.right.right = TreeNode(2)
root.right.left.left = TreeNode(6)
print(ob.solve(root))

Input

root = TreeNode(2)
root.left = TreeNode(10)
root.right = TreeNode(4)
root.right.left = TreeNode(8)
root.right.right = TreeNode(2)
root.right.left.left = TreeNode(6)

Output

20

Updated on: 10-Oct-2020

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements