【发布时间】:2012-11-11 11:07:46
【问题描述】:
我有这个问题要做:
"定义一个函数findpath:: BTree a -> a -> Path(其中Btree a 定义如前面的问题),给定二叉树t 和值x,返回从t 的根开始的路径如果有一个叶子,则值为x,否则值为Nothing。程序的运行时间应该与树中的节点数成线性关系。"
到目前为止我有:
data Maybe a = Nothing | Just a
data BTree a = Leaf a | Fork (BTree a) (BTree a)
type Path = Maybe [Dir]
data Dir = Left | Right
findpath :: Eq a => BTree a -> a -> Path
findpath (Leaf y) x = if y==x then ??? else Nothing
findpath (Fork l r) x = nodepath (findpath l x) (findpath r x) where
nodepath :: Path -> Path -> Path
nodepath Nothing Nothing = Nothing
nodepath Nothing pathr = Just [R]
nodepath pathl Nothing = Just [L]
我仍然无法在(Leaf y) 案例中构建最终答案
【问题讨论】:
-
您的
findpath类型表明它返回[Dir],它不是接受值Nothing的类型。该问题表明findpath应该返回Path,即Maybe [Dir],考虑到失败的可能性。我还想知道类型是否应该是findpath :: Eq a => BTree a -> a -> Path,这将允许您测试您寻求的值是否等于存储在树的叶子中的值。 -
是的,我认为类型签名中也应该有一个 Eq a。
标签: haskell tree binary-tree