Given an array of integers, is there a way to convert it into Binary Search Tree (unbalanced) quickly? I have tried inserting it one by one for each element, but this means that I have to traverse from the beginning for each insertion. It works perfectly, but I think the worst case is O(N^2) for being unbalanced, e.g. the array is sorted. Given a large N, I think it is going to take some time.
Back to my question, is there a way to do this faster than the algorithm that I stated?
For example, given array [4,5,2,3,1], is there a fast way to create this?
4
/ \
2 5
/ \
1 3
A binary tree has the benefits of both an ordered array and a linked list as search is as quick as in a sorted array and insertion or deletion operations are as fast as in a linked list. A tree is a group of nodes starting from the root node.
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root.
As mentioned earlier, the BST is an ordered data structure. Upon insertion, the nodes are placed in an orderly fashion. This inherent order makes searching fast. Similar to binary search (with an array that is sorted), we cut the amount of data to sort through by half on each pass.
Creating binary search trees using C/C++ arrays is not a new idea, but the algorithm to calculate the left and right sub child makes array size much more than number of elements. Consider the creation of this BST example: Insert (50), since this is the first element, it is added at index [0] and becomes the root element.
Yes, there is easy way to construct a balanced Binary Search Tree from array of integers in O (nlogn). Sort the array of integers. This takes O (nlog (n)) time
The strength of binary search comes from being able to quickly filter out the unnecessary values. When a tree is unbalanced, especially like the type of tree that would result from a sorted array, it won’t yield the same benefits as a balanced tree.
If you don't have to do sorting initially, you could construct binary tree by using binary tree insertion algorithm for each element of the array. Refer to any standard implementation of Self-balancing BST. While scanning the array, at ith iteration, you have BST for arr [1...i]. Now, you add arr [i+1] to BST (using insertion algorithm).
Yes, there is easy way to construct a balanced Binary Search Tree from array of integers in O(nlogn).
Algorithms is as follows:
EDIT:
Refer to any standard implementation of Self-balancing BST. While scanning the array, at ith iteration, you have BST for arr[1...i]. Now, you add arr[i+1] to BST (using insertion algorithm).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With