【问题标题】:Relationships in a Tree (Haskell)树中的关系(Haskell)
【发布时间】:2018-01-26 06:49:14
【问题描述】:

在叶子和节点中具有值的二叉树定义为:

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

例如,

         10
        /  \
       /    \
      8      2
     / \    / \
    3   5  2   0

exTree :: Tree Int
exTree = N 10 (N 8 (H 3) (H 5))
               (N 2 (H 2) (H 0))

好吧,我需要一个名为 RelationshipBinaryTree 的函数,它生成一个元组列表,其第一个组件是 x,第二个是父亲。在这棵树上,

relationshipBinaryTree :: Tree a -> [(a,a)]
relationshipBinaryTree exTree =  [(10,8),(8,3),(8,5),(10,2),(2,2),(2,0)]

另外,我需要在 Data.Tree hackage (https://hackage.haskell.org/package/containers-0.5.11.0/docs/Data-Tree.html) 中定义它

我希望你能帮助我,因为我不太了解树和图表。

我试过了

relationshipBinaryTree :: Tree a -> [(a,a)] 
 relationshipBinaryTree (L _) = [] 
 relationshipBinaryTree (N _ (Tree i) (Tree d)) = relationshipBinaryTree (N _) ++ relationshipBinaryTree (Tree i) ++ relationshipBinaryTree (Tree d)

【问题讨论】:

  • 到目前为止你尝试过什么?你哪里出了问题?
  • relationshipBinaryTree :: 树 a -> [(a,a)] ;关系二叉树 (L_) = [] ; relationshipBinaryTree (N _ (Tree i) (Tree d)) = relationshipBinaryTree (N _) ++ relationshipBinaryTree (Tree i) ++ relationshipBinaryTree (Tree d)

标签: haskell tree functional-programming


【解决方案1】:

您想使用Data.Tree,但Data.Tree 甚至不是关于二叉树,而是关于多路树(又名玫瑰树)。但是,如果您有一个函数value :: Tree a -> a,那么您当然可以将它映射到玫瑰树的子节点,并将结果与​​值结合起来。

现在,Data.Tree 中存在一个函数,它被称为 rootLabel。还有另一个函数可以获取节点的子节点,它被称为subForest

这来自Data.TreeTree的定义:

Node
   rootLabel :: a           -- label value
   subForest :: Forest a    -- zero or more child trees

所以我们可以为玫瑰树定义:

fatherChild :: Tree a -> [(a, a)]
fatherChild t = map mkPair children ++ concatMap fatherChild children
   where mkPair child = (rootLabel t, child)
         children     = subForest t

例子:

fatherChild (Node 3 [Node 8 [], Node 4 []])
> [(3,8),(3,4)]

你的例子:

fatherChild (Node 10 [Node 8 [Node 3 [], Node 5 []], Node 2 [Node 2 [], Node 0 []]])
> [(10,8),(10,2),(8,3),(8,5),(2,2),(2,0)]

现在,这并不能回答你关于 二叉树 树的问题,但我想把它留给你作为练习,因为它会非常相似(除非你卡住了)。 (并且请不要将玫瑰树用作二叉树,因为没有类型安全来确保始终有两个孩子。)

【讨论】:

    【解决方案2】:

    一种简单的方法是通过辅助函数获取值,然后进行递归:

    data Tree a = Leaf a
                  | Node a (Tree a) (Tree a) deriving (Eq, Show)
    
    
    exTree :: Tree Int
    exTree = Node 10 t1 t2
    t1 = Node 8 (Leaf 3) (Leaf 5)
    t2 = Node 2 (Leaf 2) (Leaf 0)
    
    
    relationshipBinaryTree :: Tree a -> [(a,a)] 
    relationshipBinaryTree (Leaf _) = [] 
    relationshipBinaryTree (Node v i d) = [(v, getVal i), (v, getVal d)] ++ relationshipBinaryTree i ++ relationshipBinaryTree d
    
    getVal (Node v _ _) = v
    getVal (Leaf v) = v
    
       relationshipBinaryTree exTree
    => [(10,8),(10,2),(8,3),(8,5),(2,2),(2,0)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      相关资源
      最近更新 更多