Quantcast
Channel: interview Question – wikistack
Viewing all articles
Browse latest Browse all 34

make binary search tree from array

$
0
0

Write a C program to make binary search tree from array. Given a array of positive integers like [3, 5, 2, 1, 4] the binary search tree would look like

    3
   / \
  1   4
 /     \
2       5

The above binary search tree is height balanced because height of left sub-tree and height of right sub-tree is differ by no more than 1.

Algorithm to make binary search tree from array

  1.  Sort the array in ascending order.
  2. Take two pointers to the middle element and start to move the first to the left and the other to the right, and just insert the elements pointed by the pointers to the left and right sub-tree respectively.

 

#include<stdio.h>
#include<stdlib.h>

typedef struct Node
{
  struct Node *left;
  struct Node *right;
  int value;
} Tree;

Tree *make_node (int value)
{
  Tree *newNode = (Tree *) malloc (sizeof (Tree));
  newNode->left = NULL;
  newNode->right = NULL;
  newNode->value = value;
  return newNode;
}

Tree *constructBST (int arr[], int start, int end, Tree * root)
{
  if (start > end)
    return NULL;
  int mid = (start + end) / 2;
  if (root == NULL)
    root = make_node (arr[mid]);
  root->left = constructBST (arr, start, mid - 1, root->left);
  root->right = constructBST (arr, mid + 1, end, root->right);
  return root;
}

void print_tree_inorder (Tree * root)
{
  if (root == NULL)
    return;
  print_tree_inorder (root->left);
  printf ("%d ", root->value);
  print_tree_inorder (root->right);
}

void freeMemory(Tree *root)
{
  if( root == NULL) return;
  freeMemory(root->left);
  freeMemory(root->right);
  free(root);
}

// comparator function for qsort
int comp (const void *a, const void *b)
{
  return (*(int *) a - *(int *) b);
}

int main ()
{
  Tree *root = NULL;
  int arr[] = { 3, 5, 2, 1, 4 };
  int size = sizeof (arr) / sizeof (arr[0]);
  qsort ((void *) arr, size, sizeof (arr[0]), comp);
  root = constructBST (arr, 0, size - 1, root);
  // print tree in order
  print_tree_inorder (root);
  // free memory
  freeMemory(root);
  root = NULL;
}

Note:

The post make binary search tree from array appeared first on wikistack.


Viewing all articles
Browse latest Browse all 34

Trending Articles