计算Tree中更深的分支

时间:2015-03-21 12:42:11

标签: haskell

我需要帮助来解决这个问题: 我必须计算更深的分支的长度,该分支仅包含元素" A"在BSTree。

我试过这个:

data El = A | B deriving (Eq,Show)

data BSTree a = Nil | Node a (BSTree a) (BSTree a)
testBST :: BSTree El
testBST = Node A (Node A (Node B Nil Nil) Nil) (Node A Nil (Node A (Node B Nil Nil) Nil)) 

pathTree_hlp :: Int -> Int -> BSTree El -> Int
pathTree_hlp curmax prevmax Nil = max curmax prevmax
pathTree_hlp curmax prevmax (Node A l r) = pathTree_hlp (curmax+1) prevmax l + pathTree_hlp (curmax+1) prevmax r 
pathTree_hlp curmax prevmax (Node B l r) = pathTree_hlp 0 (max curmax prevmax) l + pathTree_hlp 0 (max curmax prevmax) r

pathInTree :: BSTree El -> Int
pathInTree Nil = 0
pathInTree (Node B l r) = 0
pathInTree (Node A l r) = pathTree_hlp 0 0 (Node A l r)

结果应该是3,但我的代码返回17(?) 你能帮我解决这个问题吗?

感谢所有人。

1 个答案:

答案 0 :(得分:0)

在这两行中,我改变了函数的 sum ,其中l和r分支为 max

pathTree_hlp curmax prevmax (Node A l r) = max (pathTree_hlp (curmax+1) prevmax l) (pathTree_hlp (curmax+1) prevmax r)
pathTree_hlp curmax prevmax (Node B l r) = max (pathTree_hlp 0 (max curmax prevmax) l) (pathTree_hlp 0 (max curmax prevmax) r)