简体   繁体   English

在二进制搜索树中插入新值

[英]Inserting a new value in binary search tree

Using an algorithm Tree-Insert(T, v) that inserts a new value v into a binary search tree T , the following algorithm grows a binary search tree by repeatedly inserting each value in a given section of an array into the tree: 通过使用将新值v插入二进制搜索树T Tree-Insert(T, v)算法,以下算法通过将数组的给定部分中的每个值重复插入到树中来增长二进制搜索树:

Tree-Grow(A, first, last, T)
1 for i ← first to last
2 do Tree-Insert(T, A[i])

  1. If the tree is initially empty, and the length of array section (ie, last-first+1) is n, what are the best-case and the worst-case asymptotic running time of the above algorithm, respectively? 如果树最初是空的,并且数组部分的长度(即last-first + 1)为n,则上述算法的最佳情况和最坏情况渐近运行时间分别是多少?

  2. When n = 7, give a best-case instance (as an array containing digits 1 to 7, in certain order), and a worst-case instance (in the same form) of the algorithm. 当n = 7时,给出算法的最佳实例(作为包含数字1至7的数组,按特定顺序)和最差实例(以相同形式)。

  3. If the array is sorted and all the values are distinct, find a way to modify Tree-Grow, so that it will always build the shortest tree. 如果对数组进行了排序并且所有值都是不同的,请找到一种方法来修改Tree-Grow,以便它始终生成最短的树。

  4. What are the best-case and the worst-case asymptotic running time of the modified algorithm, respectively? 改进算法的最佳情况和最坏情况渐近运行时间分别是多少?

Please tag homework questions with the homework tag. 请用homework标签标记作业问题。 In order to do well on your final exam, I suggest you actually learn this stuff, but I'm not here to judge you. 为了在期末考试中取得出色的成绩,我建议您实际学习这些知识,但我不是来这里判断您的。

1) It takes O(n) to iterate from first to last. 1)从头到尾进行迭代需要O(n)。 It takes O(lg n) to insert into a binary tree, therefore it the algorithm that you have shown takes O(n lg n) in the best case. 插入二叉树需要O(lg n),因此在最佳情况下,您显示的算法需要O(n lg n)。

The worst case of inserting into a binary tree is when the tree is really long, but not very bushy; 插入二叉树的最坏情况是树真的很长,但又不是很浓密。 similar to a linked list. 类似于链表。 In that case, it would take O(n) to insert, therefore it would take O(n^2) in the worst case. 在那种情况下,将需要O(n)进行插入,因此在最坏的情况下将需要O(n ^ 2)。

2) Best Case: [4, 2, 6, 1, 3, 5, 7], Worst Case: [1, 2, 3, 4, 5, 6, 7] 2)最佳情况:[4、2、6、1、3、5、7],最坏情况:[1、2、3、4、5、6、7]

3) Use the n/2 index as the root, then recursively do this for the left side and right side of the array. 3)使用n / 2索引作为根,然后递归地对数组的左侧和右侧执行此操作。

4) O(n lg n) in the best and worst case. 4)O(n lg n)在最好和最坏的情况下。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM