Friday, 4 November 2016

Program 17 - Binary Search Tree



#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left, *right;
};
struct node *create(struct node *root, int num) {
if(root == NULL){
root = (struct node *) malloc(sizeof(struct node));
root -> data = num;
root -> left = root -> right = NULL;
} else {
if(num <= root -> data){
root -> left = create(root -> left, num);
} else {
root -> right = create(root -> right, num);
}
}
return root;
}
void inorder(struct node *root) {
if(root != NULL) {
inorder(root -> left);
printf("%d ", root -> data);
inorder(root -> right);
}
}
void preorder(struct node *root) {
if(root != NULL) {
printf("%d ", root -> data);
preorder(root -> left);
preorder(root -> right);
}
}
void postorder(struct node *root) {
if(root != NULL) {
postorder(root -> left);
postorder(root -> right);
printf("%d ", root -> data);
}
}
int main() {
struct node *root = NULL;
int num;
printf("***Create Binary Search Tree***\n");
printf("Enter data: ");
scanf("%d", &num);
while(num != -1) {
root = create(root, num);
printf("Enter data or enter -1 to stop: ");
scanf("%d", &num);
}
printf("Inorder: ");
inorder(root);
printf("\nPreorder: ");
preorder(root);
printf("\nPostorder: ");
postorder(root);
}
































































































































No comments:

Post a Comment