Please check the errror.
Error:
We received the following error when we ran your code:
make: *** [makefile:22: test] Segmentation fault (core dumped)
C file code:
#include "binary_search_tree.h"
#include <stdlib.h>
static node_t *insert_node(node_t *root, int data)
{
if (root == NULL)
{
// Create a new node when we find an empty spot
node_t *newNode = (node_t *)malloc(sizeof(node_t));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// If the data is less than the root's data, insert in the left subtree
if (data < root->data)
root->left = insert_node(root->left, data);
// If the data is greater than the root's data, insert in the right subtree
else
root->right = insert_node(root->right, data);
return root;
}
node_t *build_tree(int *tree_data, size_t tree_data_len)
{
node_t *root = NULL;
for (size_t i = 0; i < tree_data_len; i++)
{
root = insert_node(root, tree_data[i]);
}
return root;
}
void free_tree(node_t *tree)
{
if (tree == NULL)
return;
// Recursively free left and right subtrees
free_tree(tree->left);
free_tree(tree->right);
// Free the current node
free(tree);
}
static void in_order_traversal(node_t *node, int **sorted, int *index)
{
if (node == NULL)
return;
// Traverse left subtree
in_order_traversal(node->left, sorted, index);
// Add node data to the sorted array
(*sorted)[*index] = node->data;
(*index)++;
// Traverse right subtree
in_order_traversal(node->right, sorted, index);
}
// Helper function for in-order traversal
static void count_nodes(node_t *node,int size)
{
if (node == NULL)
return;
count_nodes(node->left,size);
size++;
count_nodes(node->right,size);
}
int *sorted_data(node_t *tree)
{
int *sorted = NULL;
int index = 0;
// First pass to calculate the size of the sorted array (tree size)
int size = 0;
node_t *temp = tree;
count_nodes(temp,size);
// Allocate memory for the sorted array
sorted = (int *)malloc(size * sizeof(int));
// Perform in-order traversal to populate the sorted array
in_order_traversal(tree, &sorted, &index);
return sorted;
}
Header file code:
#ifndef BINARY_SEARCH_TREE_H
#define BINARY_SEARCH_TREE_H
#include <stddef.h>
typedef struct node node_t;
struct node {
node_t *right;
node_t *left;
int data;
};
node_t *build_tree(int *tree_data, size_t tree_data_len);
void free_tree(node_t *tree);
int *sorted_data(node_t *tree);
#endif