1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: ans = 0 def dfs(root: Optional[TreeNode]): if not root: return inf, -inf left_min, left_max = dfs(root.left) right_min, right_max = dfs(root.right) min_num = min(root.val, left_min, right_min) max_num = max(root.val, left_max, right_max) nonlocal ans ans = max(ans, max_num - root.val, root.val - min_num) return min_num, max_num dfs(root) return ans
ans = 0 def dfs(root: Optional[TreeNode], min_ancient_val:int, max_ancient_val): if not root: nonlocal ans ans = max(ans, max_ancient_val - min_ancient_val) return nxt_min_val = min(min_ancient_val, root.val) nxt_max_val = max(max_ancient_val, root.val) dfs(root.left, nxt_min_val, nxt_max_val) dfs(root.right, nxt_min_val, nxt_max_val)
dfs(root, root.val, root.val) return ans
ans = 0 def dfs(root: Optional[TreeNode], min_ancient_val:int, max_ancient_val): if not root: return nonlocal ans cur = max(root.val - min_ancient_val, max_ancient_val - root.val) if cur > ans: ans = cur nxt_min_val = min(min_ancient_val, root.val) nxt_max_val = max(max_ancient_val, root.val) dfs(root.left, nxt_min_val, nxt_max_val) dfs(root.right, nxt_min_val, nxt_max_val)
dfs(root, root.val, root.val) return ans
|