[英]What is the complexity of insertion operation for 1…n keys in BST and Splay tree?
If n keys 1,2,…,n are to be inserted in that order, 如果要按此顺序插入n个键1,2,…,n,
(a). (一种)。 to a normal BST (Binary Search Tree) 到普通的BST(二进制搜索树)
(b). (b)。 to a Splay Tree 到八卦树
What would be the complexity in each case (a), b) ? 在每种情况下(a),b)的复杂度是多少?
Is it O(log n) for both the cases? 两种情况都为O(log n)吗? Or is it O(log n) for (a) and O(M log n) for (b) ? 还是(a)为O(log n)和(b)为O(M log n)?
According to the Wikipedia Splay tree article, average insertion time is O(log n), and worst case is amortized O(log n). 根据Wikipedia Splay树文章,平均插入时间为O(log n),最坏的情况是摊销O(log n)。 So your expected time to insert all the items into the Splay tree would be O(n log n). 因此,将所有项目插入Splay树的预期时间为O(n log n)。
The Binary search tree case depends on what kind of BST you're using. 二进制搜索树的大小写取决于您使用的是哪种BST。 For a primitive BST, inserting items in order is the worst case because it creates a degenerate tree--a linked list. 对于原始BST,按顺序插入项目是最坏的情况,因为它会创建简并树-链表。 That's O(n) (where n is the number of items in the tree) per insertion. 每次插入就是O(n)(其中n是树中的项目数)。 So insertion of all the items would require O(n^2). 因此,插入所有项将需要O(n ^ 2)。
Insertion into a degenerate tree is O(n) because the tree is essentially a linked list. 插入简并树是O(n),因为树本质上是一个链表。 After inserting the numbers [1, 2, 3]
in order, your tree looks like this: 依次插入数字[1, 2, 3]
后,树如下所示:
1
\
2
\
3
If you then want to insert 4
, the code has to look at each of the existing items, 1, 2, and 3, before adding 4 as the right child of 3. And when you go to insert 5
, it again has to look at the previous four items. 如果然后要插入4
,则代码必须先查看每个现有项1、2和3,然后再将4作为3的右子级添加。当您插入5
,它必须再次查找在前四个项目。 Each insertion has to look at all of the previous items. 每次插入都必须查看所有先前的项目。 The total number of comparisons when inserting n items will be (n*(n-1))/2
, which is O(n^2). 插入n个项目时的比较总数为(n*(n-1))/2
,即O(n ^ 2)。
If you're using a self balancing binary search tree, then insertion is O(log n), and insertion of all the items will require O(n log n). 如果您使用的是自平衡二叉搜索树,则插入为O(log n),而所有项目的插入将需要O(n log n)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.