Maximum Difference Between Node and Ancestor

medium binary tree dfs

Problem

Given the root of a binary tree, find the maximum value of |a.val - b.val| over all ancestor-descendant pairs (a, b). Equivalently, on each root-to-leaf path, compute (path max - path min) and return the largest such value.

Inputroot = [8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13]
Output7
|8 - 1| = 7 along path 8 → 3 → 1.

def max_ancestor_diff(root):
    def dfs(node, mn, mx):
        if not node:
            return mx - mn
        mn = min(mn, node.val)
        mx = max(mx, node.val)
        return max(dfs(node.left, mn, mx), dfs(node.right, mn, mx))
    return dfs(root, root.val, root.val)
function maxAncestorDiff(root) {
  function dfs(node, mn, mx) {
    if (!node) return mx - mn;
    mn = Math.min(mn, node.val);
    mx = Math.max(mx, node.val);
    return Math.max(dfs(node.left, mn, mx), dfs(node.right, mn, mx));
  }
  return dfs(root, root.val, root.val);
}
class Solution {
    public int maxAncestorDiff(TreeNode root) {
        return dfs(root, root.val, root.val);
    }
    private int dfs(TreeNode node, int mn, int mx) {
        if (node == null) return mx - mn;
        mn = Math.min(mn, node.val);
        mx = Math.max(mx, node.val);
        return Math.max(dfs(node.left, mn, mx), dfs(node.right, mn, mx));
    }
}
int dfs(TreeNode* node, int mn, int mx) {
    if (!node) return mx - mn;
    mn = min(mn, node->val);
    mx = max(mx, node->val);
    return max(dfs(node->left, mn, mx), dfs(node->right, mn, mx));
}
int maxAncestorDiff(TreeNode* root) {
    return dfs(root, root->val, root->val);
}
Time: O(n) Space: O(h)