|
| 1 | +# Definition for a binary tree node. |
| 2 | +from typing import Optional |
| 3 | + |
| 4 | + |
| 5 | +class TreeNode: |
| 6 | + def __init__(self, val=0, left=None, right=None): |
| 7 | + self.val = val |
| 8 | + self.left = left |
| 9 | + self.right = right |
| 10 | + |
| 11 | + |
| 12 | +class Solution: |
| 13 | + def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: |
| 14 | + self.result = 0 |
| 15 | + |
| 16 | + def helper(node: Optional[TreeNode], currMax: int, currMin: int): |
| 17 | + if not node: |
| 18 | + return |
| 19 | + self.result = max(self.result, abs( |
| 20 | + node.val - currMax), abs(node.val - currMin)) |
| 21 | + currMax = max(currMax, node.val) |
| 22 | + currMin = min(currMin, node.val) |
| 23 | + helper(node.left, currMax, currMin) |
| 24 | + helper(node.right, currMax, currMin) |
| 25 | + |
| 26 | + helper(root, root.val, root.val) |
| 27 | + return self.result |
| 28 | + |
| 29 | + |
| 30 | +root = TreeNode(8) |
| 31 | +root.left = TreeNode(3) |
| 32 | +root.left.left = TreeNode(1) |
| 33 | +root.left.right = TreeNode(6) |
| 34 | +root.left.right.left = TreeNode(4) |
| 35 | +root.left.right.right = TreeNode(7) |
| 36 | +root.right = TreeNode(10) |
| 37 | +root.right.right = TreeNode(14) |
| 38 | +root.right.right.left = TreeNode(13) |
| 39 | + |
| 40 | +print(Solution().maxAncestorDiff(root)) |
0 commit comments