Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- for each node there can be four ways that the max path goes through the node:
- 1)Node only
- 2)Max path through left child+node
- 3)max path through right child + node
- 4)max path through left child+node+max path through right child
- Note: updating max without including the root with only n1 and n2 is not the current node responsibility,it would have
- been already done on the descendent node.
- '''
- '''
- class Node:
- def __init__(self,val):
- self.data = val
- self.left = None
- self.right = None
- '''
- def fun(root, ans):
- if not root:
- return 0
- l1,l2 = 0,0
- if root.left:
- l1 = fun(root.left, ans)
- if root.right:
- l2 = fun(root.right, ans)
- # best path that can be extended to parent
- cur_node = max(root.data,root.data + max(l1, l2))
- # path passing through current node
- cross_path = l1 + l2 + root.data
- # update global answer
- ans[0] = max(ans[0],cur_node,cross_path)
- return cur_node
- class Solution:
- def findMaxSum(self, root):
- if not root:
- return 0
- ans = [float('-inf')]
- fun(root, ans)
- return ans[0]
Advertisement
Add Comment
Please, Sign In to add comment