Haskell中的树合并算法

时间:2015-12-27 04:26:21

标签: algorithm haskell tree

我需要一个带有两棵树的函数,检查是否有任何常见的分支从主干出来,如果可能的话将树合并到一棵树中。

如果节点rootLabels相等,则可以认为节点相同。两棵不同根的树不能合并。可以合并具有相同根的两棵树,并且可以递归地检查它们的分支以查看它们是否可以合并。

任何人都可以建议通过mergetest1的函数test2(下面)的实现(即函数返回True)?我确信有一个简单,优雅的解决方案,但它现在正在回避我。或者,我可以使用现有的库函数吗?

import Data.Tree

merge :: (Eq a) => Tree a -> Tree a -> Either (Tree a, Tree a) (Tree a)
merge = undefined

test1 :: Bool
test1 = 
    Node 'a' 
            [Node 'b' 
                [Node 'c' 
                    [], 
                Node 'g' 
                    []], 
            Node 'd' 
                []]
    `merge`
    Node 'a' 
            [Node 'b' 
                [Node 'c' 
                    [Node 'h'
                        []]], 
            Node 'e' 
                [Node 'f' 
                    []]]
    == 
    Right 
    (Node 'a' 
        [Node 'b' 
            [Node 'c' 
                [Node 'h'
                    []], 
            Node 'g' 
                []], 
        Node 'd' 
            [],
        Node 'e' 
            [Node 'f' 
                []]])

test2 :: Bool
test2 =  
    let l = Node 'a' []
        r = Node 'b' []
    in  l `merge` r == Left (l,r)

1 个答案:

答案 0 :(得分:2)

我想我终于明白了;

merge :: (Eq a) => Tree a -> Tree a -> Either (Tree a, Tree a) (Tree a)
merge l r = 
    if rootLabel l == rootLabel r
        then Right $ merge' l r 
        else Left (l,r)

merge' :: (Eq a) => Tree a -> Tree a -> Tree a
merge' l r = l { subForest = foldl mergeNode (subForest l) (subForest r) }

mergeNode :: Eq a => [Tree a] -> Tree a -> [Tree a]
mergeNode [] y = [y]
mergeNode (x:xs) y 
    | rootLabel x == rootLabel y = x `merge'` y : xs
    | otherwise = x : xs `mergeNode` y