Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert sorted array into binary search tree

I want to implement an algorithm that inserts sorted arrays into binary search trees but I don't want ending up with a tree that only grows to one side.

Do you have any ideas?

Thanks.

like image 715
Ege Avatar asked Oct 16 '13 09:10

Ege


People also ask

Can binary search apply to sorted array?

Binary Search is a searching algorithm for finding an element's position in a sorted array. In this approach, the element is always searched in the middle of a portion of an array. Binary search can be implemented only on a sorted list of items. If the elements are not sorted already, we need to sort them first.

What happens if you insert a sorted sequence of items into a BST?

If we repeatedly insert a sorted sequence of values to form a BST, we obtain a completely skewed BST. The height of such a tree is n - 1 if the tree has n nodes. Thus, the worst case complexity of searching or inserting an element into a BST having n nodes is O(n).

What is the procedure to insert into a sorted array?

The insertion and deletion of elements in a sorted array executes at O(n), due to the need to shift all the elements following the element to be inserted or deleted; in comparison a self-balancing binary search tree inserts and deletes at O(log n).


1 Answers

This should give you a balanced tree (in O(n)):

  1. Construct a node for the middle element in the array and return it
    (this will be the root in the base case).
  2. Repeat from 1. on the left half of the array, assigning the return value to the left child of the root.
  3. Repeat from 1. on the right half of the array, assigning the return value to the right child of the root.

Java-like code:

TreeNode sortedArrayToBST(int arr[], int start, int end) {
  if (start > end) return null;
  // same as (start+end)/2, avoids overflow.
  int mid = start + (end - start) / 2;
  TreeNode node = new TreeNode(arr[mid]);
  node.left = sortedArrayToBST(arr, start, mid-1);
  node.right = sortedArrayToBST(arr, mid+1, end);
  return node;
}

TreeNode sortedArrayToBST(int arr[]) {
  return sortedArrayToBST(arr, 0, arr.length-1);
}

Code derived from here.

like image 138
Bernhard Barker Avatar answered Sep 20 '22 00:09

Bernhard Barker