Below is the program which converts a sorted Array to BST. I am able to compile and execute the program using an online C compiler. When I tried the compile on my local system, it is throwing a segmentation fault.
SortedArraytoBST.c
#include <stdio.h>
#include <stdlib.h>
// Structure of the node
struct TNode
{
int data;
struct TNode* left;
struct TNode* right;
};
struct TNode* newNode(int data);
// Function that converts array to BST
struct TNode* SortedArrayToBST(int arr[], int start, int end)
{
if(start > end)
{
return NULL;
}
if(start == end)
{
struct TNode* newnode2 = newNode(arr[start]);
return newnode2;
}
int mid = (start+end)/2;
struct TNode* newnode = newNode(arr[mid]);
newnode->left = SortedArrayToBST(arr, start, mid-1);
newnode->right = SortedArrayToBST(arr, mid+1, end);
return newnode;
}
//NewNode Creation
struct TNode* newNode(int data)
{
struct TNode* node = (struct TNode*)malloc(sizeof(struct TNode*));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// Print the tree in preorder
void preorder(struct TNode* node)
{
if( node == NULL) return;
printf("%d\n", node->data);
preorder(node->left);
preorder(node->right);
}
// Array to BST
int main()
{
int arr[]={1,2,3};
int size = sizeof(arr)/sizeof(arr[0]);
struct TNode* root = SortedArrayToBST(arr, 0, size-1);
preorder(root);
return 0;
}
Command used to compile the program
$ gcc -o SortedArraytoBST SortedArraytoBST.c
$ gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin15.2.0
Thread model: posix
$
Output of the program on my local Mac
2
-398445936
Segmentation fault: 11
Output of the program on http://code.geeksforgeeks.org/
2
1
3