0% found this document useful (0 votes)
10 views3 pages

Experiment 8

Uploaded by

Tanmay Vashishth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

Experiment 8

Uploaded by

Tanmay Vashishth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Experiment - 8

Aim: Program for implementation of binary search tree and traverse the
tree in pre order, post order and in order.

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node *left, *right;
};

struct Node* newNode(int data) {


struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}

void inorderTraversal(struct Node* root) {


if (root == NULL)
return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}

void preorderTraversal(struct Node* root) {


if (root == NULL)
return;
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}

void postorderTraversal(struct Node* root) {


if (root == NULL)
return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}

int main() {
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

printf("Inorder traversal: ");


inorderTraversal(root);

printf("\nPreorder traversal: ");


preorderTraversal(root);

printf("\nPostorder traversal: ");


postorderTraversal(root);
return 0;
}

Output:
Inorder traversal: 4 2 5 1 3
Preorder traversal: 1 2 4 5 3
Postorder traversal: 4 5 2 3 1

You might also like