In: Computer Science
Here is the answer to the first question:
#include<stdio.h>
#include<stdlib.h>
typedef struct m{
struct m* left;
int data;
struct m* right;
}Node;
void inOrderTraversal(Node* root){
if(!root){
return;
}
inOrderTraversal(root -> left);
printf(" %d " , root->data);
inOrderTraversal(root -> right);
}
void preOrderTraversal(Node* root){
if(!root){
return;
}
printf(" %d " , root->data);
preOrderTraversal(root -> left);
preOrderTraversal(root -> right);
}
void postOrderTraversal(Node* root){
if(!root){
return;
}
postOrderTraversal(root -> left);
postOrderTraversal(root -> right);
printf(" %d " , root->data);
}
//Function for creating a node of binary tree
Node* createNode(int data){
Node* node = malloc(sizeof(Node));
if(!node){
return NULL;
}
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
int main(){
//Creating a tree to test the functions on
/*The tree is
0
/ \
1 2
/ \ / \
7 9 4 8
*/
Node *root;
root = createNode(0);
root->left = createNode(1);
root->right = createNode(2);
root->left->left = createNode(7);
root->left->right = createNode(9);
root->right->left = createNode(4);
root->right->right = createNode(8);
printf("Preorder Traversal \n");
preOrderTraversal(root);
printf("\nInorder Traversal \n");
inOrderTraversal(root);
printf("\nPostorder Traversal \n");
postOrderTraversal(root);
return 0;
}
Image for indentation reference: