Search 尝试实现Haskell二叉树搜索的路径记录
我一直在Haskell中使用二叉树,我正在尝试实现一个dfs变量,它返回从根节点到包含搜索值的节点的路径(由左和右组成)。我认为最好返回Search 尝试实现Haskell二叉树搜索的路径记录,search,haskell,binary-tree,Search,Haskell,Binary Tree,我一直在Haskell中使用二叉树,我正在尝试实现一个dfs变量,它返回从根节点到包含搜索值的节点的路径(由左和右组成)。我认为最好返回可能是Directions类型 以下是迄今为止实施的措施 data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show, Eq) data Direction = L | R deriving (Show) type Directions = [Direction] inTre
可能是Directions
类型
以下是迄今为止实施的措施
data Tree a = Empty | Node a (Tree a) (Tree a)
deriving (Show, Eq)
data Direction = L | R
deriving (Show)
type Directions = [Direction]
inTree :: (Eq a) => a -> Tree a -> [Direction]
inTree val (Node x l r)
| val == x = []
| l /= Empty = L:(inTree val l)
| r /= Empty = R:(inTree val r)
| otherwise =
但我不知道如何让它穿过整棵树。我觉得我可能想得太迫切了 您使用
可能方向的想法很好。我会将您的函数重写如下:
inTree :: (Eq a) => a -> Tree a -> Maybe [Direction]
inTree val Empty = Nothing
inTree val (Node x l r)
| val == x = Just []
| otherwise = (fmap (L:) (inTree val l)) <|> (fmap (R:) (inTree val r))
inTree::(Eq a)=>a->Tree a->Maybe[方向]
inTree val Empty=无
inTree val(节点x l r)
|val==x=Just[]
|否则=(fmap(L:)(inTree val L))(fmap(R:)(inTree val R))
fmap
如果原始值为Nothing
和Just(fv)
如果是Just v
,则在上使用函数f
可能会导致Nothing
。在我们的例子中,如果递归调用找到了该值(因此它返回的路径只是[Direction]
),我们将附加在当前节点上获取的方向
运算符来自。这是一个关于可能的左倾选择。这里我们使用它来选择返回的子树只是[Direction]
(如果有)
一个好的练习是修改代码,以便它返回树中x
s的所有路径