合并树节点

sbe*_*kur 4 c# algorithm

有谁知道会以以下方式合并treenodes的算法?

treeA
   \ child a
          \node(abc)
   \ child b
          \node(xyz)                   

         + 

treeB
   \ child a              
          \node(qrs)
   \ child b
          \node(xyz)
               \node(pdq)
   \ child c
          \node(pdq)

         = // do merge

treeMerged     
   \ child a
          \node(abc) 
          \node(qrs)
   \ child b
          \node(xyz)
               \node(pdq)
   \ child c
          \node(pdq)
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。

sbe*_*kur 5

好吧,一旦我花时间考虑一下,该解决方案就会比我预期的简单得多。(我已经在下面的代码中发布了关键部分)

   private TreeNode DoMerge(TreeNode source, TreeNode target) {
        if (source == null || target == null) return null;

        foreach (TreeNode n in source.Nodes) {
            // see if there is a match in target
            var match = FindNode(n, target.Nodes); // match paths
            if (match == null) { // no match was found so add n to the target
                target.Nodes.Add(n);
            } else { 
                // a match was found so add the children of match 
                DoMerge(n, match);
            }

        }
        return target;

    }
Run Code Online (Sandbox Code Playgroud)

还是想知道是否有人有更好的解决方案?