In: Computer Science
C program that demonstrate tree traversal. see for the sample output.
Sample Output:
How many node do you have in your tree : 5
Enter root: 20
if you want to add to the left press 0 otherwise press 1
answer: 0
Enter next node: 10
if you want to add to the left press 0 otherwise press 1
answer: 0
Enter next node: 8
if you want to add to the left press 0 otherwise press 1
answer: 0
Enter next node: 15
if you want to add to the left press 0 otherwise press 1
answer: 1
Enter next node: 21
Display tree
20
/ \
10 21
/
8
/
5
Preorder – 20, 10, 8, 5, 21
Inorder – 5, 8, 10, 20, 21
Postorder – 5, 8, 10, 21, 20
** COMMENT CODE PLEASE**
#include <stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *left;
struct node *right;
};
typedef struct node tree;
tree *root = NULL;
tree* newnode(int data) {
tree *new = NULL;
new = (tree *)malloc(sizeof(tree));
new->data = data;
new->left = NULL;
new->right = NULL;
return(new);
}
void preorder(tree *root) {
if(root == NULL) {return;}
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
void inorder(tree *root) {
if(root == NULL) {return;}
inorder(root->left);
printf("%d ",root->data);
inorder(root->right);
}
void postorder(tree *root) {
if(root == NULL) {return;}
postorder(root->left);
postorder(root->right);
printf("%d ",root->data);
}
int main() {
root = newnode(20);
root->left = newnode(10);
root->right = newnode(21);
root->left->left = newnode(8);
root->left->left->left = newnode(15);
printf("Preorder traversal of binary tree is : ");
preorder(root);
printf("\n");
printf("Inorder traversal of binary tree is : ");
inorder(root);
printf("\n");
printf("Postorder traversal of binary tree is : ");
postorder(root);
getchar();
return 0;
}