wit*_*yyy 6 algorithm tree recursion f#
我有一个元组列表int*string其中int是level,string是name
let src = [
(0, "root");
(1, "a");
(2, "a1");
(2, "a2");
(1, "b");
(2, "b1");
(3, "b11");
(2, "b2");
]
Run Code Online (Sandbox Code Playgroud)
我需要将其转换为以下内容
let expectingTree =
Branch("root",
[
Branch("a",
[
Leaf("a1");
Leaf("a2")
]);
Branch("b",
[
Branch("b1", [Leaf("b11")]);
Leaf("b2")
]);
]);
Run Code Online (Sandbox Code Playgroud)
以下是我如何做到的方式,但任何人都可以通过更好的方式来实现这一目标.我是F#的新手,做同样事情的C#代码会更短,所以我想我错了.
type Node =
| Branch of (string * Node list)
| Leaf of string
let src = [
(0, "root");
(1, "a");
(2, "a1");
(2, "a2");
(1, "b");
(2, "b1");
(3, "b11");
(2, "b2");
]
let rec setParents (level:int) (parents:list<int>) (lst:list<int*int*string>) : list<int*int*string> =
//skip n items and return the rest
let rec skip n xs =
match (n, xs) with
| n, _ when n <= 0 -> xs
| _, [] -> []
| n, _::xs -> skip (n-1) xs
//get parent id for given level
let parentId (level) =
let n = List.length parents - (level + 1)
skip n parents |> List.head
//create new parent list and append new id to begin
let newParents level id =
let n = List.length parents - (level + 1)
id :: skip n parents
match lst with
| (id, l, n) :: tail ->
if l = level then (id, parentId(l), n) :: setParents l (newParents l id) tail
elif l <= level + 1 then setParents l parents lst
else [] //items should be in order, e.g. there shouldnt be item with level 5 after item with level 3
| _ -> []
let rec getTree (root:int) (lst: list<int*int*string>) =
let getChildren parent =
List.filter (fun (_, p, _) -> p = parent) lst
let rec getTreeNode (id:int) (name:string) =
let children = getChildren id
match List.length children with
| 0 -> Leaf(name)
| _ -> Branch(name,
children
|> List.map (fun (_id, _, _name) -> getTreeNode _id _name))
match getChildren root with
| (id, _, n) :: _ -> getTreeNode id n
| _ -> Leaf("")
let rec printTree (ident:string) (tree:Node) =
match tree with
| Leaf(name) ->
printfn "%s%s" ident name
| Branch(name, children) ->
printfn "%s%s" ident name
List.iter (fun (node) -> printTree (" " + ident) node) children
let tree =
src
|> List.mapi (fun i (l, n) -> (i+1, l, n)) //set unique id to each item
|> setParents 0 [0] //set parentId to each item
|> getTree 0
printTree "" tree
Console.ReadKey() |> ignore
Run Code Online (Sandbox Code Playgroud)
首先,Leaf如果你的分支包含一个子树列表,你真的不需要有一个明显的例子,因为leaf只是一个没有子树的分支.所以,我将使用以下树类型:
type Tree =
| Branch of string * list<Tree>
Run Code Online (Sandbox Code Playgroud)
使用显式递归列表处理可以更容易地实现将列表转换为树的核心功能.你可以一次完成 - 只要找到嵌套索引(或者当你得到一个较小的索引时从适当数量的递归调用返回),只需遍历元素并启动一个新的分支.这是我的尝试:
/// Build a tree from elements of 'list' that have larger index than 'offset'. As soon
/// as it finds element below or equal to 'offset', it returns trees found so far
/// together with unprocessed elements.
let rec buildTree offset trees list =
match list with
| [] -> trees, [] // No more elements, return trees collected so far
| (x, _)::xs when x <= offset ->
trees, list // The node is below the offset, so we return unprocessed elements
| (x, n)::xs ->
/// Collect all subtrees from 'xs' that have index larger than 'x'
/// (repeatedly call 'buildTree' to find all of them)
let rec collectSubTrees xs trees =
match buildTree x [] xs with
| [], rest -> trees, rest
| newtrees, rest -> collectSubTrees rest (trees @ newtrees)
let sub, rest = collectSubTrees xs []
[Branch(n, sub)], rest
Run Code Online (Sandbox Code Playgroud)
该函数采用初始偏移量和目前为止收集的树.该trees参数总是会[]和你需要的初始一些价值offset.结果是给定级别下面的树列表和剩余元素列表:
let res = buildTrees -1 [] src
Run Code Online (Sandbox Code Playgroud)
假设root高于-1,你可以忽略元组的第二部分(它应该是空列表)并得到第一棵树(应该只有一个):
/// A helper that nicely prints a tree
let rec print depth (Branch(n, sub)) =
printfn "%s%s" depth n
for s in sub do print (depth + " ") s
res |> fst |> Seq.head |> print ""
Run Code Online (Sandbox Code Playgroud)