Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 108. Convert Sorted Array to Binary Search Tree in F#

Shohei Yoshida's photo
Shohei Yoshida
·Aug 10, 2022·

1 min read

URL

leetcode.com/problems/convert-sorted-array-..

Code

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

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

let sortedArrayToBST (nums: int []) : Tree =
    let rec sortedArrayToBST' left right (nums: int []) =
        if left > right then
            Leaf
        else
            let mid = (left + right) / 2
            Node(nums.[mid], sortedArrayToBST' left (mid - 1) nums, sortedArrayToBST' (mid + 1) right nums)

    sortedArrayToBST' 0 (nums.Length - 1) nums
 
Share this