1026. Maximum Difference Between Node and Ancestor

1026. Maximum Difference Between Node and Ancestor

# 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:
    def dfs(self,root,mmax,mmin):
        if root==None:
            self.ans=max(self.ans,mmax-mmin)
            return 
        mmax=max(mmax,root.val)
        mmin=min(mmin,root.val)
        self.dfs(root.left,mmax,mmin)
        self.dfs(root.right,mmax,mmin)

    def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
        self.ans=0
        self.dfs(root,root.val,root.val)
        return self.ans

你可能感兴趣的:(leetcode)