|
| 1 | +//Binary tree traversal: |
| 2 | + |
| 3 | +#include <stdio.h> |
| 4 | +#include <conio.h> |
| 5 | +#include <malloc.h> |
| 6 | +struct node |
| 7 | +{ |
| 8 | + struct node *left; |
| 9 | + int data; |
| 10 | + struct node *right; |
| 11 | +}; |
| 12 | + |
| 13 | +void main() |
| 14 | +{ |
| 15 | + void insert(struct node **,int); |
| 16 | + void inorder(struct node *); |
| 17 | + void postorder(struct node *); |
| 18 | + void preorder(struct node *); |
| 19 | + |
| 20 | + struct node *ptr; |
| 21 | + int no,i,num; |
| 22 | + |
| 23 | + ptr = NULL; |
| 24 | + ptr->data=NULL; |
| 25 | + clrscr(); |
| 26 | + |
| 27 | + printf("\nProgram for Tree Traversal\n"); |
| 28 | + printf("Enter the number of nodes to add to the tree.<BR>\n"); |
| 29 | + scanf("%d",&no); |
| 30 | + |
| 31 | + for(i=0;i<no;i++) |
| 32 | + { |
| 33 | + printf("Enter the item\n"); |
| 34 | + scanf("%d",&num); |
| 35 | + insert(&ptr,num); |
| 36 | + } |
| 37 | + |
| 38 | + //getch(); |
| 39 | + printf("\nINORDER TRAVERSAL\n"); |
| 40 | + inorder(ptr); |
| 41 | + |
| 42 | + printf("\nPREORDER TRAVERSAL\n"); |
| 43 | + preorder(ptr); |
| 44 | + |
| 45 | + printf("\nPOSTORDER TRAVERSAL\n"); |
| 46 | + postorder(ptr); |
| 47 | + |
| 48 | + getch(); |
| 49 | +} |
| 50 | + |
| 51 | +void insert(struct node **p,int num) |
| 52 | +{ |
| 53 | + if((*p)==NULL) |
| 54 | + { |
| 55 | + printf("Leaf node created."); |
| 56 | + (*p)=malloc(sizeof(struct node)); |
| 57 | + (*p)->left = NULL; |
| 58 | + (*p)->right = NULL; |
| 59 | + (*p)->data = num; |
| 60 | + return; |
| 61 | + } |
| 62 | + else |
| 63 | + { |
| 64 | + if(num==(*p)->data) |
| 65 | + { |
| 66 | + printf("\nREPEATED ENTRY ERROR VALUE REJECTED\n"); |
| 67 | + return; |
| 68 | + } |
| 69 | + if(num<(*p)->data) |
| 70 | + { |
| 71 | + printf("\nDirected to left link.\n"); |
| 72 | + insert(&((*p)->left),num); |
| 73 | + } |
| 74 | + else |
| 75 | + { |
| 76 | + printf("Directed to right link.\n"); |
| 77 | + insert(&((*p)->right),num); |
| 78 | + } |
| 79 | + } |
| 80 | + return; |
| 81 | +} |
| 82 | + |
| 83 | +void inorder(struct node *p) |
| 84 | +{ |
| 85 | + if(p!=NULL) |
| 86 | + { |
| 87 | + inorder(p->left); |
| 88 | + printf("\nData :%d",p->data); |
| 89 | + inorder(p->right); |
| 90 | + } |
| 91 | + else |
| 92 | + return; |
| 93 | +} |
| 94 | + |
| 95 | +void preorder(struct node *p) |
| 96 | +{ |
| 97 | + if(p!=NULL) |
| 98 | + { |
| 99 | + printf("\nData :%d",p->data); |
| 100 | + preorder(p->left); |
| 101 | + preorder(p->right); |
| 102 | + } |
| 103 | + else |
| 104 | + return; |
| 105 | +} |
| 106 | + |
| 107 | +void postorder(struct node *p) |
| 108 | +{ |
| 109 | + if(p!=NULL) |
| 110 | + { |
| 111 | + postorder(p->left); |
| 112 | + postorder(p->right); |
| 113 | + printf("\nData :%d",p->data); |
| 114 | + } |
| 115 | + else |
| 116 | + return; |
| 117 | +} |
| 118 | + |
0 commit comments