You are on page 1of 6

Lab Report

On
A program that will traverse a tree in preorder, inorder, &
postorder
COURSE CODE: CSE 232
Course Title: Data Structures Lab
Experiment No - 05

Submitted To: Submitted By:


Sadah Anjum Shanto Romzan Ali Mohon

Lecturer Id: 17182103177


Intake: 38
Dept. of CSE Section: 4

DEPARTM ENT OF CO M PUTER SCIENCE AND ENG INEERING


BANGLA DESH UNIVERSITY OF BUSINESS AND TECHNOLOGY

Submission Date: 06.05.2019


Source code:

#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left, *right;
};
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
void preorder(struct node *root)
{
if (root != NULL)
{
printf("%d \n", root->key);
inorder(root->left);
inorder(root->right);
}
}
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d \n", root->key);
inorder(root->right);
}
}
void postorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
inorder(root->right);
printf("%d \n", root->key);
}
}
struct node* insert(struct node* node, int key)
{
if (node == NULL) return newNode(key);

if (key < node->key)


node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);

return node;
}
int main()
{
struct node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
printf("the data is in preorder: \n");
preorder(root);
printf("the data is in inorder: \n");
inorder(root);
printf("the data is in postorder: \n");
postorder(root);
return 0;
}

You might also like