14,888 views
1 votes
1 votes
If an array with n-element is given then what will be the time complexity of creating Binary tree and Binary Search tree?

1 Answer

Best answer
9 votes
9 votes

Binary Search tree (BST)

Is suppose data element are in sorted order then it will create skew tree in Binary search tree. Hence Time complexity will be $O(n^2)$.

Worst case of BST creation arrives when you get data in sorted order, and data is coming one by one. Let consider input data is 3,4,6,7,9,10,11,12,14 then, by using insertion method this tree will get created. 

So this will take $O(n^2)$ times. 

Binary Tree


But in Binary tree, we can choose middle elment as root and divide rest of the element as left child and right child. In this way we can achieve Binary tree creation in $O(n)$ time. Basically in the case of Binary tree you do not have to think which vakue is going where. 

//Provedure to create Binary tree in O(n) time
struct node * CBT(int A[], int lb, int ub,){
    if(lb<=ub){
        if(lb==ub){
            struct node * temp = getNode(A[lb]);
            return temp;
        }
        else {
            int mid = (lb + ub)/2;
            struct node * temp = getNode(A[mid]);
            temp -> left = CBT(A, lb, mid-1);
            temp -> right = CBT(A, mid+1, ub);
            return temp;
        }
    }
}

Sove this reccurance to get time complexity of $O(n)$. 

edited by

Related questions

2 votes
2 votes
3 answers
3
1 votes
1 votes
0 answers
4
srestha asked Oct 31, 2017
437 views
The number of BST possible with 6 nodes numbered 1,2,3,4,5,6 with exactly 1 leaf node __________