看看我的递归插入(c#)的实现。有 T(n) = 2*T(n/2) + O(1)。O(1) 用于寻找中心:(l+r)/2。所以同谋是 O(n)
public class Tree<T>
{
public class TreeNode<T>
{
public TreeNode<T> Right { get; set; }
public TreeNode<T> Left { get; set; }
public T Data { get; set; }
}
public Tree()
{
Root = new TreeNode<T>();
}
public TreeNode<T> Root { get; set; }
private void InsertSortedListRec(IList<T> items, TreeNode<T> curNode, int l, int r)
{
var mid = (l + r)/2;
curNode.Data = items[mid];
if (mid - 1 >= l)
{
curNode.Left = new TreeNode<T>();
InsertSortedListRec(items, curNode.Left, l, mid - 1);
}
if (mid + 1 <= r)
{
curNode.Right = new TreeNode<T>();
InsertSortedListRec(items, curNode.Right, mid + 1, r);
}
}
public void InsertSortedList(IList<T> items)
{
InsertSortedListRec(items, Root, 0, items.Count - 1);
}
}
我假设我们有索引数组(我们可以将链表转换为数组 O(n))