I am trying to write a program to construct a binary search tree and print the tree on its side. Read the input from the user as a sequence of integers and output the tree indented based on depth and with one value on each line. However, my code is working but not printing anything on console? I think something might be wrong with my insert function but I am not sure.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left, *right;
};
typedef struct node node;
node *insert(node *t, int a){ //insert values in tree
node* tmp= (node*)malloc(sizeof(node));;
if (t==NULL) {
tmp->data = a;
tmp->left = NULL;
tmp->right = NULL;
return(tmp);
}
else if (a < t->data)
t->left = insert(t->left,a);
else
t->right = insert(t->right,a);
return(t);
}
void print( node *t, int depth) {
int i;
if (t == NULL)
return;
print(t->right, depth + 1);
for (i = 0; i < 4 * depth; ++i)
printf(" ");
printf("%d\n", t->data);
print(t->left, depth + 1);
}
int main() {
node *root= NULL;
int n,a,i;
printf("Enter number of values "); //7
scanf("%d", &n);
printf("\nEnter numbers "); //10 6 14 4 8 12 16
for (i = 0; i < n; ++i) {
scanf("%d", &a);
insert(&root, a);
}
print(root, 0);
return 0;
}
Input: 10 6 14 4 8 12 16
Expected output:
16
14
12
10
8
6
4
The signature of insert
is
node *insert(node *t, int a) // t is a pointer to node
But you are passing a pointer to pointer to node
insert(&root, a);
I think you want
root = insert(root, a);