Shohei Yoshida
Shohei Yoshida's Blog

Follow

Shohei Yoshida's Blog

Follow

LeetCode 1026. Maximum Difference Between Node and Ancestor in F#

Shohei Yoshida's photo
Shohei Yoshida
·Dec 9, 2022·

1 min read

URL

leetcode.com/problems/maximum-difference-be..

Code

github.com/syohex/dotnet-study/tree/master/..

open System

type Tree =
    | Leaf
    | Node of int * Tree * Tree

let maxAncestorDiff (root: Tree) : int =
    let rec maxAncestorDiff' node min max =
        match node with
        | Leaf -> 0
        | Node(v, left, right) ->
            let min' = Math.Min(min, v)
            let max' = Math.Max(max, v)
            let diff = Math.Max(Math.Abs(v - min), Math.Abs(v - max))
            let leftVal = maxAncestorDiff' left min' max'
            let rightVal = maxAncestorDiff' right min' max'

            Math.Max(diff, Math.Max(leftVal, rightVal))

    match root with
    | Leaf -> failwith "never reach here"
    | Node(v, _, _) -> maxAncestorDiff' root v v
 
Share this