Shohei Yoshida
Shohei Yoshida's Blog

Follow

Shohei Yoshida's Blog

Follow

LeetCode 144. Binary Tree Preorder Traversal in F#

Shohei Yoshida's photo
Shohei Yoshida
·Jan 9, 2023·

1 min read

URL

https://leetcode.com/problems/binary-tree-preorder-traversal/description/

Code

https://github.com/syohex/dotnet-study/blob/master/fsharp/leetcode/problems/0144/main.fsx

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

let preorderTraversal (root: Tree) : int list =
    let rec preorderTraversal' node acc =
        match node with
        | Leaf -> acc
        | Node (v, left, right) ->
            (v :: acc)
            |> preorderTraversal' left
            |> preorderTraversal' right

    preorderTraversal' root [] |> List.rev
 
Share this