Listing the paths to leaves in a tree

后端 未结 3 766
失恋的感觉
失恋的感觉 2021-02-10 06:18

I\'m trying to write a function that finds all of the paths to the leaves in a tree. For example, given a tree that looks like this:

           1
         /  \\
         


        
3条回答
  •  野性不改
    2021-02-10 06:55

    just a simple function:

    listtree :: [a] -> Tree a -> [[a]]
    listtree l (Node a []) = [l++[a]]
    listtree l (Node a forest) = concatMap (listtree (l++[a])) forest
    

    use a list to record path from root to current node, and append current node's label to the path, then recursively map listtree to each subnode.

    listtree [] (Node 1 [(Node 2 [(Node 3 []), (Node 4 [])]), (Node 5 [(Node 6 [])])]))
    

    yield the desired result [[1,2,3],[1,2,4],[1,5,6]]

提交回复
热议问题