Array for binary search trees

Given an array of integers, is there a way to quickly convert it to a binary search tree (unbalanced)? I tried to insert it one by one for each element, but that means I have to go through from the very beginning for each insert. It works fine, but I think the worst case is O (N ^ 2) for imbalance, for example. array is sorted. Given the big N, I think it will take some time.

Returning to my question, is there a way to do this faster than the algorithm that I have outlined?

For example, given an array [4,5,2,3,1], is there a quick way to create this?

    4  
   /  \  
  2    5  
 / \  
1   3
+4
source share
2 answers

, O (nlogn).

:

  • Sort . O (nlog (n))
  • BST O (n) . root + .

EDIT:

  • -, , O (nlog (n)), ( ) , O (nlogn). .
  • , , .

Self-balancing BST. i- BST arr [1... i]. arr [i + 1] BST ( ).

+1

, () ?

. O (n logn), , , , ( O (n)), O(n logn). , :

3, 5, 2, 1, 4

1, 2, 3, 4, 5. - 3,

      3
     / \
    2   4
   /     \
  1       5

, , , , .

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

+2

All Articles