编写递归函数来计算树的深度

时间:2016-11-05 13:06:35

标签: haskell recursion functional-programming higher-order-functions

我必须编写一个递归函数,给定一棵树 数据类型,将返回树的深度。空树应该返回 0.单个根节点Tree应返回1.

预期产出:

let treeCons x = (\x -> foldl (flip insertTree) Empty x) x
depth (treeCons []) -> 0
depth (treeCons [5,4,6,3,7,1]) -> 4
depth (treeCons [1,2,5,8,9,4,7]) -> 5
depth (treeCons [5,4,6,3,7,1,2,5,8,9,4,7,8,5,3,4]) -> 6

我编写了以下数据类型和插入函数:

data Tree a = Node a (Tree a) (Tree a) | Empty deriving (Show, Eq)
insertTree :: (Ord a) => a -> Tree a -> Tree a
insertTree a Empty = Node a Empty Empty
insertTree a (Node b Empty Empty) = if (a <= b) then (Node b (Node a Empty Empty) Empty) else (Node b Empty (Node a Empty Empty))
insertTree a (Node b left right) = if (a <= b) then (Node b (insertTree a left) right ) else (Node b left (insertTree a right))

然而,我没有得到如何编写深度函数。我是haskell的新手,如果有人帮助我,我会很感激。

2 个答案:

答案 0 :(得分:4)

空树的深度为0,节点的深度为1加上其子节点的最大深度:

depth :: Tree a -> Int
depth Empty = 0
depth (Node _ l r) = 1 + max (depth l) (depth r)

答案 1 :(得分:0)

在这里,非常简单,通过列表递归并且树大致相同,只有数据类型不同。每当你点击相关树的一个分支时你添加1:

tDepth :: Tree a -> Int
tDepth Empty = 0
tDepth (Node _ left right) = 1 + max (tLength left)  (tLength right)