imashutosh51

Maximum path sum from any node

Jul 31st, 2022 (edited)
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.15 KB | None | 0 0
  1. '''
  2. for each node there can be four ways that the max path goes through the node:
  3. 1)Node only
  4. 2)Max path through left child+node
  5. 3)max path  through right child + node
  6. 4)max path through left child+node+max path through right child
  7. Note: updating max without including the root with only n1 and n2 is not the current node responsibility,it would have
  8. been already done on the descendent node.
  9. '''
  10. '''
  11. class Node:
  12.    def __init__(self,val):
  13.        self.data = val
  14.        self.left = None
  15.        self.right = None
  16. '''
  17. def fun(root, ans):
  18.     if not root:
  19.         return 0
  20.     l1,l2 = 0,0
  21.     if root.left:
  22.         l1 = fun(root.left, ans)
  23.     if root.right:
  24.         l2 = fun(root.right, ans)
  25.    
  26.     # best path that can be extended to parent
  27.     cur_node = max(root.data,root.data + max(l1, l2))
  28.    
  29.     # path passing through current node
  30.     cross_path = l1 + l2 + root.data
  31.     # update global answer
  32.     ans[0] = max(ans[0],cur_node,cross_path)
  33.     return cur_node
  34.  
  35. class Solution:
  36.     def findMaxSum(self, root):
  37.         if not root:
  38.             return 0
  39.         ans = [float('-inf')]
  40.         fun(root, ans)
  41.         return ans[0]
Advertisement
Add Comment
Please, Sign In to add comment