开发者

Inserting a new value in binary search tree

开发者 https://www.devze.com 2022-12-22 04:24 出处:网络
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

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:

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 (i.e., last-first+1) is n, what are the best-case and the worst-case asymptotic running time of the above algorithm, respectively?

  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.

  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.

  4. What are the best-case and the worst-case asymptotic running time of the modified algorithm, respecti开发者_StackOverflow中文版vely?


Please tag homework questions with the homework tag. 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. 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.

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.

2) Best Case: [4, 2, 6, 1, 3, 5, 7], Worst Case: [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.

4) O(n lg n) in the best and worst case.

I hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号