| #include <stdio.h> | |
| #include <stdlib.h> | |
| struct node { | |
| int data; | |
| struct node *left, *right; | |
| }; | |
| int is_left_child(int num) { | |
| int choice; | |
| printf("Do you want to create a left child of %d? (1/0): ", num); | |
| scanf("%d", &choice); | |
| return choice; | |
| } | |
| int is_right_child(int num) { | |
| int choice; | |
| printf("Do you want to create a right child of %d? (1/0): ", num); | |
| scanf("%d", &choice); | |
| return choice; | |
| } | |
| struct node *create(struct node *root){ | |
| int num; | |
| printf("Enter data: "); | |
| scanf("%d", &num); | |
| if(root == NULL){ | |
| root = (struct node *) malloc(sizeof(struct node)); | |
| root -> data = num; | |
| root -> left = root -> right = NULL; | |
| } | |
| if(is_left_child(root -> data)) { | |
| //Asks the user if he wants to create left child | |
| root -> left = create(root -> left); | |
| } | |
| if(is_right_child(root -> data)) { | |
| //Asks the user if he wants to create right child | |
| root -> right = create(root -> right); | |
| } | |
| 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, rpt = 1; | |
| printf("***Create Binary Tree***\n"); | |
| root = create(root); | |
| printf("Inorder: "); | |
| inorder(root); | |
| printf("\nPreorder: "); | |
| preorder(root); | |
| printf("\nPostoder: "); | |
| postorder(root); | |
| } |
Friday, 4 November 2016
Program 15 - Binary Tree
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment