The time complexity of creating a BST with a minimum height with a sorted array with elements in ascending order

I tried to solve this problem in two ways. The most obvious solution is to use the standard BST insert operation, starting at the root of the node, and recursively continue. However, it will take time to insert each node log N. Since I have to do this for N nodes, this will occupy me completely NlogN. So I thought about how to cut off a few calls so that I would not have to go through the whole tree to insert each node. In this approach, after inserting the root, I pass only half of the array (left half) to generate the left subtree and right half of the array (right half) to generate the correct subtree. The code for it is as follows:

public static TreeNode createMinBST(int arr[], int start, int end){
 if (end < start) {
 return null;
 }
 int mid = (start + end) / 2;
 TreeNode n = new TreeNode(arr[mid]);
 n.left = createMinBST(arr, start, mid - 1);
 n.right = createMinBST(arr, mid + 1, end);
 return n;
 }

That, I could easily get up. But it's hard for me to parse the runtime of this code. Any help please? Could you talk about how to get into the runtime so that I can reuse this analysis for other problems?

+4
source share
2 answers

This algorithm works in O (n) time. Here are two ways to see this.

First, you may notice that each function call is executed in O (1) time, and each call "uses" one of the nodes. This means that there can only be O (n) common calls, so the overall work will be O (n).

-. O (1) () n/2,

T (n) = 2T (n/2) + O (1)

O (n).

, !

+2

T(n) - , createMinBST n = end - start. T(n) :

T(0) = a
T(n) <= 2T(floor(n/2)) + b

, <= ; , , , . , S = 1, 3, 7, ..., S(n-1)*2 + 1, .... , ( , ).

. , . :

T(0) = a
T(1) <= 2T(0) + b = 2a + b                 = 2a + b
T(2) <= 2T(1) + b = 4a + 2b + b            = 4a + 3b
T(4) <= 2T(2) + b = 8a + 4b + 2b + b       = 8a + 7b
T(8) <= 2T(4) + b = 16a + 8b + 4b + 2b + b = 16a + 17b
...
T(n) <= (2n)a + (2n-1)b = 2(a+b)n - b

, , n. , O(n).

"-", , .

:

  • T(n) .
  • .

( ) , . , . , , , , ; , , ( 1, 3, 7, 15,...).

+1

All Articles