Skip to content

Instantly share code, notes, and snippets.

@brunofarache
Created November 9, 2020 23:02
Show Gist options
  • Save brunofarache/fe958e399d40e20382f364431bf72be3 to your computer and use it in GitHub Desktop.
Save brunofarache/fe958e399d40e20382f364431bf72be3 to your computer and use it in GitHub Desktop.
def maxAncestorDiff(root: TreeNode): Int = {
def visit(node: TreeNode, min: Int, max: Int): Int = {
if (node == null) return 0
val diff = math.max(math.abs(node.value - max), math.abs(node.value - min))
val newMin = math.min(node.value, min)
val newMax = math.max(node.value, max)
math.max(math.max(diff, visit(node.left, newMin, newMax)), visit(node.right, newMin, newMax))
}
visit(root, root.value, root.value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment