#1026. Maximum Difference Between Node and Ancestor

ยท

1 min read

https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/submissions/1143717619/?envType=daily-question&envId=2024-01-11

function maxAncestorDiff(root) {
    if (!root) return 0

    function dfs(node, minAncestor, maxAncestor) {
        if (!node) return maxAncestor - minAncestor

        minAncestor = Math.min(minAncestor, node.val)
        maxAncestor = Math.max(maxAncestor, node.val)

        const leftDiff = dfs(node.left, minAncestor, maxAncestor)
        const rightDiff = dfs(node.right, minAncestor, maxAncestor)

        return Math.max(leftDiff, rightDiff)
    }

    return dfs(root, root.val, root.val)
}
ย