gpt4 book ai didi

c# - N-ary树插入和搜索的复杂度是多少?

转载 作者:太空狗 更新时间:2023-10-30 01:33:20 24 4
gpt4 key购买 nike

我正在用 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();
}

这些方法的 bigO 复杂度是多少?

最佳答案

让我们看看 Search 方法中有什么。它不是二叉树,我们有递归。所以 Search 方法将调用 N 次,直到我们找到所需的值。所以我们可以得出结论,我们有 O(N),其中 N 是在最后一次迭代中找到值的最大(最差)迭代次数:

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;
}

For Addition 方法更简单,因为我们有 for 语句并且没有嵌套循环。所以我们有 O(N) 用于 Addition 方法。

As Wisconsin university says:

So for loops for (i = 0; i < N; i++) { sequence of statements } The loop executes N times, so the sequence of statements also executes N times. Since we assume the statements are O(1), the total time for the for loop is N * O(1), which is O(N) overall.

关于c# - N-ary树插入和搜索的复杂度是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34255499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com