3
我正在C#中實現N-1ry樹。我想知道如何計算下面的方法的複雜性。這裏是我的代碼:N元樹插入和搜索的複雜性是什麼?
結構:
public class Node
{
public int Value { get; set; }
public Node Children { get; set; }
public Node Sibilings { get; set; }
}
這種方法用於搜索:
public Node search(Node root, int data)
{
if (root == null)
return null;
if (data == root.Value)
return root;
Node t = search(root.Children, data);
if (t == null)
t = search(root.Sibilings, data);
return t;
}
這種方法插入:
public void Add(int[] data)
{
Node temp = null;
temp = search(ROOT, data[0]);
if (temp == null)
temp = new Node(data[0]);
if (this.ROOT == null)
ROOT = temp;
Node parent = temp;
for (int j = 1; j <= this.NoOfChildrens; j++)
{
// for first child
if (j == 1)
{
parent.Children = new Node(data[j]);
parent = parent.Children;
}
//for all other childs
else
{
parent.Sibilings = new Node(data[j]);
parent = parent.Sibilings;
}
}
}
程序入口點:
static void Main(string[] args)
{
NAryTree naryTree = new NAryTree(3);
// 1st element in each row is node Value,>=2nd....=>value of child
int[][] data = { new int[] { 1, 2, 3, 4 }, new int[] { 2, 1, 6,0 }, new int[] { 3, 8, 9, 10 }, new int[] { 4, 0, 0, 0 } };
naryTree.Add(data[0]);
naryTree.Add(data[1]);
naryTree.Add(data[2]);
naryTree.Add(data[3]);
naryTree.Add(new int[] {10,3,6,4});
naryTree.preorder(naryTree.ROOT);
Console.ReadLine();
}
這些方法的bigO複雜性是什麼?
你已經只顯示了一些代碼,但缺乏代碼來重新平衡孩子在Add方法中提示O(total_number_of_nodes)是最好的選擇(可能會更糟糕,這取決於其他方法有多糟糕)。平衡樹應該獲得O(log n)以進行添加/刪除/搜索。 –
我無法理解這段代碼。在我看來,搜索方法至少應該有一個'for'。另外我認爲一個節點不應該訪問它的兄弟姐妹。 – Tempux
我只是實現了N-Ary樹,我更新了我的問題 –