简体   繁体   English

查找树中的所有部分路径

[英]Find all the partial paths in a tree

I am trying to create a Haskell function that generates a list containing all the partial paths of a tree, given the tree implementation data Tree a = Empty | Node a (Tree a) (Tree a)我正在尝试创建一个 Haskell function ,它生成一个包含树的所有部分路径的列表,给定树实现data Tree a = Empty | Node a (Tree a) (Tree a) data Tree a = Empty | Node a (Tree a) (Tree a) . data Tree a = Empty | Node a (Tree a) (Tree a) For example, if I have a tree例如,如果我有一棵树

tree = Node 5 (Node 3 Empty Empty ) (Node 2 Empty Empty )

I want to get我想得到

[[],[5],[5,3],[5,2]]

How could I make such a function?我怎么能做出这样的 function?

First let us consider the type of this function, it must be Tree a -> [[a]] .首先让我们考虑这个 function 的类型,它必须是Tree a -> [[a]]

So what can we do given a node Node x left right ?那么给定节点Node x left right我们能做什么呢? We have the path that is just the node itself - this is just [x] , as well as the paths that go through this node to the left- and right sub tree.我们有只是节点本身的路径 - 这只是[x] ,以及 go 通过这个节点到左右子树的路径。 The paths going throu the left and right sub tree are just what we get if we apply our function to left and right respectively.如果我们将 function 分别应用于left子树,则通过right子树的路径正是我们得到的。 We now just need to add x to the start of each of those paths and we do that by calling map(x:) paths .我们现在只需将x添加到每个路径的开头,我们通过调用map(x:) paths来做到这一点。 (And for an empty one we should get an empty list as there is no path.) (对于一个空列表,我们应该得到一个空列表,因为没有路径。)

data Tree a = Empty | Node a (Tree a) (Tree a)
tree = Node 5 (Node 3 Empty Empty ) (Node 2 Empty Empty )

pp :: Tree a -> [[a]]
pp (Node x left right) = [[x]] ++ map(x:)(pp left) ++ map(x:)(pp right)
pp Empty = []

Now this has one flaw that the empty path is not considered as a partial path by this function.现在这有一个缺陷,即该 function 不将空路径视为部分路径。 But we can easily amend that by adding it and wrapping it in another function:但是我们可以通过添加它并将其包装在另一个 function 中来轻松修改它:

partialPaths :: Tree a -> [[a]]
partialPaths t = [[]] ++ pp t

main = print $ partialPaths tree

Try it online! 在线尝试!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM