我将在C#中实现一棵N-1ry树。我想知道如何计算以下方法的复杂度。这是我的代码:
结构:
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();
}
这些方法的大O复杂度是什么?
Add
方法中缺少重新平衡子节点的代码提示O(total_number_of_nodes)是最佳选择(根据其他方法的质量如何,情况可能会更糟)。平衡树应该在添加/删除/搜索时获得O(log n)的时间复杂度。 - Alexei Levenkovif
和for
语句。因此,必须遍历每个项,正如大O符号所假定的最坏情况估计一样。 - StepUp