我正在嘗試使用c#實現n-ary類型的數據結構。該樹將具有一個根節點和一組子節點,並且子節點數組中的每個子節點也將具有一組子節點。我試圖做的是每當我們添加應該添加到葉節點中存在的所有子節點的子節點數組。我的代碼是在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);
}
}
}
謝謝:)
非常感謝。問題已經解決了。 – udi 2013-02-23 09:12:15