Haskell - 遍历树和输出到列表

时间:2015-01-01 23:38:46

标签: haskell binary-tree

我有这段代码,它在遍历后输出节点,没有任何可理解的顺序:

preorder :: Tree a -> [a]
preorder Empty = []
preorder (Branch x e d) = [x]++(preorder e)++(preorder d)

createTree = Branch 'A' 
                  (Branch 'B'
                          (Branch 'E' Empty Empty) 
                          (Branch 'B' Empty Empty)
                  )
                  (Branch 'A'
                          (Branch 'E' Empty Empty) 
                          (Branch 'A' Empty Empty)
                  )

preorder应用于createTree输出:

ABEBAEA

我想要的是从根目录开始的所有路径的列表:

["ABE","ABB","AAE","AAA"]

我不知道如何做到这一点,我是Haskell的初学者!

非常感谢您提供的所有帮助。

2 个答案:

答案 0 :(得分:4)

此练习相当于:

  • 空树的路径是什么?
  • ed成为树,每个树的路径分别列出epdp。如何计算标有xed为子树的树的路径?

所以,

paths :: Tree a -> [[a]]
paths Empty = ???
paths (Branch x e d) = ??? -- use x,ep,dp accordingly
       where ep = paths e
             dp = paths d

作为额外提示,与您自己的示例相关:

[ 'A':xs | xs <- ["BE","BB"] ] = [ "ABE" , "ABB" ]

请注意,["BE","BB"]是第一个子树的路径。

答案 1 :(得分:1)

paths :: Tree a -> [[a]]
paths  Empty                 = [[]]
paths (Branch x Empty d    ) = map (x:) $ paths d
paths (Branch x e     Empty) = map (x:) $ paths e
paths (Branch x e     d    ) = map (x:) $ paths e ++ paths d

即。只需在每个子路径前加x

createTree = Branch 'A' 
                  (Branch 'B'
                          (Branch 'E' Empty (Branch 'A' Empty Empty)) 
                          (Branch 'B' Empty Empty)
                  )
                  (Branch 'A'
                          (Branch 'E' Empty Empty) 
                          (Branch 'A' Empty Empty)
                  )

main = print $ paths createTree

打印["ABEA","ABB","AAE","AAA"]