【发布时间】:2013-02-08 21:59:48
【问题描述】:
我正在尝试使用 c# 实现 n 元类型的数据结构。树将有一个根节点和子数组,并且子数组中的每个子节点也将具有一组子节点。我想要做的是每当我们添加子数组时,该数组应该被添加到叶节点中存在的所有子节点中。我的代码是
public void addChildren(Node root, Node[] children)
{
if (root.children == null)
{
root.children = children;
}
else
{
for (int i = 0; i < root.children.Length; i++)
{
addChildren(root.children[i], children);
}
}
}
主程序
Dictionary<String, String[]> measurelist = new Dictionary<string, string[]>();
String[] values = { "y", "n" };
measurelist.Add("m1", values);
measurelist.Add("m2", values);
measurelist.Add("m3", values);
foreach (KeyValuePair<String, String[]> entry in measurelist)
{
Node[] children = new Node[entry.Value.Length];
for(int i = 0; i < entry.Value.Length ;i ++)
{
Node child = new Node(entry.Key+":"+entry.Value[i]);
children[i] = child;
}
clustertree.addChildren(clustertree.root, children);
}
但此代码会导致无限递归调用。我试过但无法弄清楚出了什么问题?请帮助我找出我做错了什么。 I have described the problem in the image
解决方案: 在您的帮助下,我找到了解决此问题的方法。如果我解释根本原因,我认为这将对可能面临同样问题的其他人有所帮助。 当我传递子节点数组时,问题的主要原因是作为引用而不是值传递。为了确保不会将相同的子数组引用传递给下一个递归调用,我对代码进行了一些更改。
这是我更正后的代码:
public void addChildren(Node root, Node[] children)
{
if (root.children == null)
{
root.children = children;
}
else
{
for (int i = 0; i < root.children.Length; i++)
{
Node[] children1 = new Node[children.Length];
//I am creating a new array and nodes and passing the newly created array to the next recursive call
for (int j = 0; j < children.Length; j++)
{
Node node = new Node(children[j].key);
node.children = children[j].children;
children1[j] = node;
}
addChildren(root.children[i], children1);
}
}
}
再次感谢:)
【问题讨论】:
标签: c# recursion tree mutation