|
| 1 | +#include <stdio.h> |
| 2 | + |
| 3 | +typedef int element; |
| 4 | +typedef struct TreeNode { |
| 5 | + element data; |
| 6 | + struct TreeNode* left; |
| 7 | + struct TreeNode* right; |
| 8 | +} TreeNode; |
| 9 | + |
| 10 | +TreeNode n1 = { 1, NULL, NULL }; |
| 11 | +TreeNode n2 = { 4, &n1, NULL }; |
| 12 | +TreeNode n3 = { 16, NULL, NULL }; |
| 13 | +TreeNode n4 = { 25, NULL, NULL }; |
| 14 | +TreeNode n5 = { 20, &n3, &n4 }; |
| 15 | +TreeNode n6 = { 15, &n2, &n5 }; |
| 16 | +TreeNode* root = &n6; |
| 17 | + |
| 18 | +void preorder(TreeNode* root) { |
| 19 | + if (root == NULL) { |
| 20 | + return; |
| 21 | + } |
| 22 | + |
| 23 | + printf("[%d] ", root->data); |
| 24 | + preorder(root->left); |
| 25 | + preorder(root->right); |
| 26 | +} |
| 27 | + |
| 28 | +void inorder(TreeNode* root) { |
| 29 | + if (root == NULL) { |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + inorder(root->left); |
| 34 | + printf("[%d] ", root->data); |
| 35 | + inorder(root->right); |
| 36 | +} |
| 37 | + |
| 38 | +void postorder(TreeNode* root) { |
| 39 | + if (root == NULL) { |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + postorder(root->left); |
| 44 | + postorder(root->right); |
| 45 | + printf("[%d] ", root->data); |
| 46 | +} |
| 47 | + |
| 48 | +int main(void) { |
| 49 | + printf("Binary Tree Traversal\n\n"); |
| 50 | + |
| 51 | + printf("Pre-Order -> "); |
| 52 | + preorder(root); |
| 53 | + printf("\n"); |
| 54 | + |
| 55 | + printf("In-Order -> "); |
| 56 | + inorder(root); |
| 57 | + printf("\n"); |
| 58 | + |
| 59 | + printf("Post-Order -> "); |
| 60 | + postorder(root); |
| 61 | + printf("\n"); |
| 62 | + |
| 63 | + return 0; |
| 64 | +} |
0 commit comments