- 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的值
- 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 [] 构造无穷数列