Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging Treenodes

Tags:

c#

algorithm

Does anyone know of an algorithm that will merge treenodes in the following way?

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)

Any help would be greatly appreciated.

like image 849
sbeskur Avatar asked Dec 31 '22 00:12

sbeskur


1 Answers

Well, once I actually took the time to think about it, the solution turns out to be far more simple than I anticipated. (I've posted the critical part of the code below)

   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;

    }

Still interested to know if someone has a better solution?

like image 110
sbeskur Avatar answered Jan 01 '23 13:01

sbeskur