#1026. Maximum Difference Between Node and Ancestor
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)
}
ย