URL
https://leetcode.com/problems/diameter-of-binary-tree/description/?envType=daily-question&envId=2024-02-27
Code
https://github.com/syohex/dotnet-study/tree/master/fsharp/leetcode/challenge/202402/diameter_of_binary_tree/main.fsx
open System
type Tree =
| Leaf
| Node of int * Tree * Tree
let diameterOfBinaryTree (root: Tree) : int =
let rec diameterOfBinaryTree' node =
match node with
| Leaf -> 0, 0
| Node(_, left, right) ->
let leftLen, leftMax = diameterOfBinaryTree' left
let rightLen, rightMax = diameterOfBinaryTree' right
let longest = Math.Max(leftLen + rightLen, Math.Max(leftMax, rightMax))
1 + System.Math.Max(leftLen, rightLen), longest
diameterOfBinaryTree' root |> snd