Skip to content

Instantly share code, notes, and snippets.

@sortira
Created November 20, 2025 05:26
Show Gist options
  • Select an option

  • Save sortira/6e86e212514ca798d96bd200d1ef1dba to your computer and use it in GitHub Desktop.

Select an option

Save sortira/6e86e212514ca798d96bd200d1ef1dba to your computer and use it in GitHub Desktop.
bst word sort
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node_t
{
char *word;
struct node_t *left;
struct node_t *right;
};
struct node_t *create_node(char *new_word)
{
struct node_t *new_node = (struct node_t *)malloc(sizeof(struct node_t));
if (new_node == NULL)
{
perror("malloc failed");
exit(EXIT_FAILURE);
}
new_node->word = strdup(new_word);
if (new_node->word == NULL)
{
perror("strdup failed");
free(new_node);
exit(EXIT_FAILURE);
}
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
struct node_t *insert_word(struct node_t *root, char *new_word)
{
if (root == NULL)
{
return create_node(new_word);
}
int comparison_result = strcmp(new_word, root->word);
if (comparison_result < 0)
{
root->left = insert_word(root->left, new_word);
}
else if (comparison_result > 0)
{
root->right = insert_word(root->right, new_word);
}
return root;
}
void inorder_traversal(struct node_t *root)
{
if (root != NULL)
{
inorder_traversal(root->left);
printf("%s\n", root->word);
inorder_traversal(root->right);
}
}
void free_tree(struct node_t *root)
{
if (root != NULL)
{
free_tree(root->left);
free_tree(root->right);
free(root->word);
free(root);
}
}
int main()
{
int num_words;
printf("Enter number of words to sort:\n");
scanf("%d", &num_words);
char* words[num_words];
for(int i = 0; i < num_words; i++) words[i] = (char*) malloc(sizeof(char) * 100);
printf("Enter %d words:\n", num_words);
for(int i = 0; i < num_words; i++) {
scanf("%s", words[i]);
}
struct node_t *root = NULL;
int i;
for (i = 0; i < num_words; i++)
{
root = insert_word(root, words[i]);
}
printf("sorted words:\n");
inorder_traversal(root);
free_tree(root);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment