Was it helpful?

Question

Program to find the largest sum of the path between two nodes in a binary tree in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary tree; we have to find the maximum sum of any path between any two nodes.

So, if the input is like

then the output will be 62 as the nodes are [12,13,14,16,7].

To solve this, we will follow these steps −

  • Define a function utils() . This will take root

  • if root null, then

    • return 0

  • l := utils(left of root)

  • r := utils(right of root)

  • max_single := maximum of (max of l and r) + value of root) and value of root

  • max_top := maximum of max_single and l + r + value of root

  • res := maximum of res and max_top

  • return max_single

  • From the main method, do the following −

  • if root is null, then

    • return 0

  • res := infinity

  • utils(root)

  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

class TreeNode:
   def __init__(self, value):
      self.val = value
      self.left = None
      self.right = None
class Solution:
   def solve(self, root):
      if root is None:
         return 0
      self.res = float("-inf")
      self.utils(root)
      return self.res
   def utils(self, root):
      if root is None:
         return 0
      l = self.utils(root.left)
      r = self.utils(root.right)
      max_single = max(max(l, r) + root.val, root.val)
      max_top = max(max_single, l + r + root.val)
      self.res = max(self.res, max_top)
      return max_single
ob = Solution()
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
print(ob.solve(root))

Input

root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)

Output

62
raja
Published on 09-Oct-2020 18:52:53
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top