haskell 99| binary Tree | 61-63

  1. Count the leaves of a binary tree

A leaf is a node with no successors. Write a predicate count_leaves/2 to count them.

数叶子:

countLeaves Empty                  = 0
countLeaves (Branch _ Empty Empty) = 1
countLeaves (Branch _ l r)         = countLeaves l + countLeaves r

Collect the leaves of a binary tree in a list

A leaf is a node with no successors. Write a predicate leaves/2 to collect them in a list.
将叶子封装进list

leaves :: Tree a -> [a]
leaves  Empty                 = []
leaves (Branch a Empty Empty) = [a]
leaves (Branch a left  right) = leaves left ++ leaves right

要注意这里面的[a],tree a 其实这个a是她的note的值


  1. Collect the internal nodes of a binary tree in a list

An internal node of a binary tree has either one or two non-empty successors. Write a predicate internals/2 to collect them in a list.

internal :: Tree a ->[a]
internal Empty                  = []
internal (Branch a Empty Empty )  = []
internal (Branch a l r )          = a: internal l ++ internal r

这个a 可以用[a]++internal l ++ internal r 代替
:前跟元素,后跟list
另一种办法

internals t = internals' t []
    where internals'  Empty                 xs = xs
          internals' (Branch x Empty Empty) xs = xs
          internals' (Branch x l r)         xs = (x :) $ internals' l $ internals' r xs

这段代码将internal方法改写,设置了一个容器储存node


Collect the nodes at a given level in a list

A node of a binary tree is at level N if the path from the root to the node has length N-1. The root node is at level 1. Write a predicate atlevel/3 to collect all nodes at a given level in a list.
第一级是root,往下一层加一级,给一个树,一个级,求node list

atLevel :: Tree a -> Int ->[a]
atLevel Empty _ = []
atLevel (Branch a _ _ ) 1 = [a]
atLevel (Branch a l r) n        
        | n >1 = (atLevel l (n-1) )++ (atLevel r (n-1))
        | otherwise = []

Branch 加括号
n-1 加括号

levels :: Tree a -> [[a]]
levels Empty          = repeat []
levels (Branch a l r) = [a] : zipWith (++) (levels l) (levels r)

atLevel :: Tree a -> Int -> [a]
atLevel t n = levels t !! (n-1)

repeat [] 构造无穷数列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值