如何解决f#树的插入功能问题

时间:2018-11-30 12:55:39

标签: f# f#-interactive f#-data c#-to-f# f#-3.0

请,我需要一些帮助为树创建插入函数。给定字符串列表中的值应插入树中的每个分支和叶子。我已经尝试解决此问题并给出了非常接近的答案,但是我无法正确编写该函数以插入所有字符串值。

代码:

type Tree = Leaf of string | Branch of (string * Tree) list

let rec insertTree (lst : string list) (tree : Tree) : Tree =

        match lst, tree with
        | a::b::c::[], y  -> 
            match y with
            | Leaf(n) -> Branch[(a, Branch[(n, Leaf(c))])]
            | Branch[(x, p)] -> Branch[(x, Branch[(a, Branch[(b, insertTree (c::[]) p)])])]
            | _     -> insertTree (b::c::[]) y
        | _ , y    -> tree

测试:insertTree ["4"; "5";"6"] (Branch [("1", (Branch[("2", Leaf("3"))]))])

礼物:Branch [("1", Branch [("4", Branch [("5", Branch [("2", Leaf "3")])])])]

我想要这个:

(Branch [("1", (Branch[("2", (Branch[("3",(Branch[("4",(Branch[("5", Leaf("6"))]))]))]))]))])

1 个答案:

答案 0 :(得分:1)

我假设您只是想将列表追加到最终叶子上,并且所有分支的列表中最多只有一个元素。

let insertTree (lst : string list) (tree : Tree) : Tree =
    let rec insertSingleIntotree x t = 
        match t with
        | Leaf(n) -> Branch[(n,Leaf x)]
        | Branch[(n,p)] -> Branch[(n, insertSingleIntotree x p)]
        | _ -> failwith "no idea what should happen here!"

    lst
    |> List.fold (fun acc x -> insertSingleIntotree x acc) tree