|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +struct node |
| 5 | +{ |
| 6 | + int data; |
| 7 | + struct node* left; |
| 8 | + struct node* right; |
| 9 | +}; |
| 10 | + |
| 11 | +struct node* newNode(int data) |
| 12 | +{ |
| 13 | + struct node* node = (struct node*) |
| 14 | + malloc(sizeof(struct node)); |
| 15 | + node->data = data; |
| 16 | + node->left = NULL; |
| 17 | + node->right = NULL; |
| 18 | + |
| 19 | + return(node); |
| 20 | +} |
| 21 | + |
| 22 | +void printPostorder(struct node* node) |
| 23 | +{ |
| 24 | + if (node == NULL) |
| 25 | + return; |
| 26 | + |
| 27 | + printPostorder(node->left); |
| 28 | + |
| 29 | + printPostorder(node->right); |
| 30 | + |
| 31 | + printf("%d ", node->data); |
| 32 | +} |
| 33 | + |
| 34 | +/* Given a binary tree, print its nodes in inorder*/ |
| 35 | +void printInorder(struct node* node) |
| 36 | +{ |
| 37 | + if (node == NULL) |
| 38 | + return; |
| 39 | + |
| 40 | + /* first recur on left child */ |
| 41 | + printInorder(node->left); |
| 42 | + |
| 43 | + /* then print the data of node */ |
| 44 | + printf("%d ", node->data); |
| 45 | + |
| 46 | + /* now recur on right child */ |
| 47 | + printInorder(node->right); |
| 48 | +} |
| 49 | + |
| 50 | +/* Given a binary tree, print its nodes in preorder*/ |
| 51 | +void printPreorder(struct node* node) |
| 52 | +{ |
| 53 | + if (node == NULL) |
| 54 | + return; |
| 55 | + |
| 56 | + /* first print data of node */ |
| 57 | + printf("%d ", node->data); |
| 58 | + |
| 59 | + /* then recur on left sutree */ |
| 60 | + printPreorder(node->left); |
| 61 | + |
| 62 | + /* now recur on right subtree */ |
| 63 | + printPreorder(node->right); |
| 64 | +} |
| 65 | + |
| 66 | +/* Driver program to test above functions*/ |
| 67 | +int main() |
| 68 | +{ |
| 69 | + struct node *root = newNode(1); |
| 70 | + root->left = newNode(2); |
| 71 | + root->right = newNode(3); |
| 72 | + root->left->left = newNode(4); |
| 73 | + root->left->right = newNode(5); |
| 74 | + |
| 75 | + printf("\nPreorder traversal of binary tree is \n"); |
| 76 | + printPreorder(root); |
| 77 | + |
| 78 | + printf("\nInorder traversal of binary tree is \n"); |
| 79 | + printInorder(root); |
| 80 | + |
| 81 | + printf("\nPostorder traversal of binary tree is \n"); |
| 82 | + printPostorder(root); |
| 83 | + |
| 84 | + getchar(); |
| 85 | + return 0; |
| 86 | +} |
0 commit comments