Skip to content

Instantly share code, notes, and snippets.

@Roytangrb
Last active November 28, 2020 05:26
Show Gist options
  • Select an option

  • Save Roytangrb/ea681c5e5e8c490cdae8c98318e63e3b to your computer and use it in GitHub Desktop.

Select an option

Save Roytangrb/ea681c5e5e8c490cdae8c98318e63e3b to your computer and use it in GitHub Desktop.
BST & inorder
/*
* Create BST from file read
* By RT
* 24 Nov, 2020
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *left;
struct node *right;
} node;
typedef node *tree; //tree is pointer to node
tree create_tree(int val){
tree t = malloc(sizeof(node));
t -> val = val;
t -> left = t -> right = NULL;
return t;
}
void insert_node(tree root, int val){
if (val < root -> val) {
if (root -> left == NULL) {
root -> left = create_tree(val);
} else {
insert_node(root -> left, val);
}
} else {
if (root -> right == NULL) {
root -> right = create_tree(val);
} else {
insert_node(root -> right, val);
}
}
}
tree tree_from_array(int arr[], int n){
if (n < 1) return NULL;
tree root = create_tree(arr[0]);
for (int i = 1; i < n; i ++) {
insert_node(root, arr[i]);
}
return root;
}
void print_inorder(tree t){
if (t == NULL) {
return;
}
print_inorder(t -> left);
printf("%d, ", t -> val);
print_inorder(t -> right);
}
int main(int argc, char *argv[]){
FILE *ifp;
ifp = fopen(argv[1], "r");
if (ifp == NULL){
printf("File is not found.\n");
exit(1);
}
int count;
//read values count
fscanf(ifp, "%d", &count);
int data[count];
// read values
for (int i = 0; i < count; i ++) {
fscanf(ifp, "%d", &data[i]);
}
tree t = tree_from_array(data, count);
printf("Print tree inorder: \n");
print_inorder(t);
fclose(ifp);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment