DeepRest

Maximum Difference Between Node and Ancestor

Dec 31st, 2021 (edited)
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. #     def __init__(self, val=0, left=None, right=None):
  4. #         self.val = val
  5. #         self.left = left
  6. #         self.right = right
  7. '''
  8. Two nodes have ancestor-descendant relationship if they lie on same root-leaf path. Thus the maximum diff bw them would be between nodes having extremes sharing same path.
  9. For each node we know the maximum and minimum value on the path from root to it(func params).
  10. For each of its left child and right child this path is common and thus current max and min are passed to it after considering its own value.
  11. For a leaf child the max and min represents the maximum and minimum of one root to leaf path. The required answer is nothing but the max of all max,min difference along such root to terminal paths.
  12. For each node, la is max of all mx,mn differences in ledt subtree and ra is of right subtree the max of them is its answer. Thus the solution is built from bottom to top in dfs fashion.
  13. '''
  14. class Solution:
  15.     def maxAncestorDiff(self, root: Optional[TreeNode], mx=float("-inf"), mn=float("+inf")) -> int:
  16.         if not root:
  17.             return mx-mn
  18.            
  19.         mx = max(mx, root.val)
  20.         mn = min(mn, root.val)
  21.        
  22.         la=self.maxAncestorDiff(root.left, mx, mn)
  23.         ra=self.maxAncestorDiff(root.right, mx, mn)
  24.        
  25.         return max(la, ra)
Add Comment
Please, Sign In to add comment