Haskell 趣题:树的遍历

code17's picture

很经典的老题了,说不定很多教材里都有,最近在好几个地方又见着了,所以在这里贴一下。

设一棵树的类型为:

data Tree t = Leaf t
            | Node t (Tree t) (Tree t)
              deriving (Show)

写一函数 avgTree :: (Fractional t) => Tree t -> Tree t,将树中所有节点中的值 (即类型为 t 的那些值) 全部替换为它们的均值。常见的方法是遍历这棵树取均值、再遍历一次 mirror 这棵树以构造新树,这里的要求是只遍历一次。

...... full content is only available to community members.

roy_hu's picture

我以前也见过

...... full content is only available to community members.

------------分割线----------------------
http://sites.google.com/site/haskell/
http://sites.google.com/site/ocaml/

code17's picture

Exactly

...... full content is only available to community members.

fishmacs's picture

题目很好

...... full content is only available to community members.

chylli's picture

初看起来很有道理

...... full content is only available to community members.