LeetCode 1026. [Python] Maximum Difference Between Node and Ancestor
原题链接
中等
作者:
徐辰潇
,
2021-02-14 09:12:32
,
所有人可见
,
阅读 368
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
#TS: O(vertices)
#SC: O(max depth)
#V is taken as the difference between the maximum and minimum of a node with its children (includeing itself) on a SINGLE PATH
#Thus recording the MIN and MAX from bottom to up is difficult to achieve.
#Instead, recorder the MIN and MAX from up to bottom.
def maxAncestorDiff(self, root: TreeNode) -> int:
self.res = 0
self.helper(root, root.val, root.val)
return self.res
def helper(self, root, Min, Max):
if not root:
return
Max = max(Max, root.val)
Min = min(Min, root.val)
self.res = max(self.res, Max - Min)
self.helper(root.left, Min, Max)
self.helper(root.right, Min, Max)