this is an O(n^2) solution. By pre processing the array we can also solve it
O(n)
int find_mid(int ar[], int s, int e, int val)
{
int i;
for (i = s; ar[i] < val; i++);
return i;
}
node * constructTree(int ar[], int s, int e)
{
node *root;
root = new node();
root->val = ar[s];
root->left = root->right = NULL;
int mid = find_mid(ar, s+1, e, ar[s]);
if (s+1 < mid)
root -> left = constructTree(ar, s+1, mid);
if (mid < e)
root -> right = constructTree(ar, mid, e);
return root;
}
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.