Leetcode 1092 Solution

This article provides solution to leetcode question 1092 (maximum-difference-between-node-and-ancestor)

https://leetcode.com/problems/maximum-difference-between-node-and-ancestor

Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxAncestorDiff(self, root: TreeNode) -> int:
        self.ans = 0

        def dfs(node):
            local_min = node.val
            local_max = node.val

            if node.left:
                left_min, left_max = dfs(node.left)
                local_min = min(local_min, left_min)
                local_max = max(local_max, left_max)

            if node.right:
                right_min, right_max = dfs(node.right)
                local_min = min(local_min, right_min)
                local_max = max(local_max, right_max)

            self.ans = max(
                self.ans,
                int(abs(local_min - node.val)),
                int(abs(local_max - node.val)),
            )
            return local_min, local_max

        dfs(root)

        return self.ans