Merging Treenodes

前端 未结 4 1769
借酒劲吻你
借酒劲吻你 2021-01-19 03:41

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

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


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-19 04:39

    I came up with this recursive example, works perfect in C# (have been using it myself), note that you'll need to find a way to convert TreeNode.Nodes to an array:

    public static TreeNode[] mergeTrees(TreeNode[] target, TreeNode[] source)
            {
                if (source == null || source.Length == 0)
                {
                    return target;
                }
                if (target == null || target.Length == 0)
                {
                    return source;
                }
                bool found;
                foreach (TreeNode s in source)
                {
                    found = false;
                    foreach (TreeNode t in target)
                    {
                        if (s.Text.CompareTo(t.Text) == 0)
                        {
                            found = true;
                            TreeNode[] updatedNodes = mergeTrees(Util.treeView2Array(t.Nodes), Util.treeView2Array(s.Nodes));
                            t.Nodes.Clear();
                            t.Nodes.AddRange(updatedNodes);
                            break;
                        }
                    }
                    if (!found)
                    {
                        TreeNode[] newNodes = new TreeNode[target.Length + 1];
                        Array.Copy(target, newNodes, target.Length);
                        newNodes[target.Length] = s;
                        target = newNodes;
                    }
                }
                return target;
            }
    

提交回复
热议问题