递归地建造树木

时间:2014-03-08 17:15:12

标签: tree

我最近开始使用haskell,我试图创建一棵树。

我的定义为:

import Data.Char (toLower, toUpper)
import Data.Tree (Tree(Node))
import qualified Data.Set as Set
import Data.Set (Set, empty, insert)

data Mt = Leaf Integer | Branch Integer Integer Mt deriving Show

buildTree  :: a −> b −> Mt

我觉得自己完全迷失了。任何人都可以帮我写这个功能吗?

1 个答案:

答案 0 :(得分:1)

import qualified Data.List as L
data Mt = Null | Node Integer [Mt] deriving Show


buildTree _ [] = Null
buildTree [] _ = Null
buildTree prelist postlist = 
  let n = head prelist 
      restofnodespre = tail prelist 
      restofnodespost = init postlist 
      subtrees = maketree restofnodespre restofnodespost
      treelist = map (\(pr, ps) -> buildTree pr ps) subtrees
  in
      Node n treelist



maketree _ [] = []
maketree [] _ = []
maketree pre post = 
  let s = head pre 
      rest = takeWhile (/=s) post 
      newpost = rest ++ [s]
      newpre = L.intersect pre newpost 
      remainingpre = pre L.\\ newpre
      remainingpost = post L.\\ newpost
  in
      (newpre , newpost): (maketree remainingpre remainingpost)