【问题标题】:How to build a list of all branches in a tree?如何构建树中所有分支的列表?
【发布时间】:2014-05-20 21:53:45
【问题描述】:

Haskell 中的树有问题。有一棵树:

data Tree a b = Leaf a | Branch (b,Tree a b) (b,Tree a b)
    deriving(Eq, Show)

tree = Branch 
         ("A",Branch 
                ("C",Leaf 3)
                ("D",Branch
                      ("G",Leaf 7)
                      ("H",Leaf 6)
                )
          )
          ("B",Branch
                 ("E",Leaf 5)
                 ("F",Leaf 4)
          )

我需要定义一个函数,它返回这个树中所有分支的列表,输出是这样的:[["A", "C"], ["A", "D", "G"],["A","D","H"],["B","E"],["B","F"]]。我做错了,但不知道如何解决:

branch:: Tree a b -> [[b]]
branch (Leaf x) = []
branch (Branch (a,right) (b,left)) = ([y] ++ branch left) ++ ([b] ++ branch right)

我得到的输出是["A","C","D","G","H","B","E","F"]

【问题讨论】:

  • 目前您的branch 函数只返回所有节点的列表。

标签: haskell tree tree-traversal


【解决方案1】:

我认为这样的事情应该可行:

branch :: Tree a b -> [[b]]
branch (Leaf _) = [[]]
branch (Branch (a, right) (b, left)) = map (a :) (branch right) 
                                    ++ map (b :) (branch left)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 2013-02-27
    • 2018-01-04
    相关资源
    最近更新 更多