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

data structure7

The document contains a C implementation of a Binary Search Tree (BST) with functions for creating nodes, inserting values, and performing inorder, preorder, and postorder traversals. It defines a structure for the nodes and includes a main function that inserts a set of values into the BST and prints the results of each traversal method. The code demonstrates the basic operations and functionality of a BST.

Uploaded by

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

data structure7

The document contains a C implementation of a Binary Search Tree (BST) with functions for creating nodes, inserting values, and performing inorder, preorder, and postorder traversals. It defines a structure for the nodes and includes a main function that inserts a set of values into the BST and prints the results of each traversal method. The code demonstrates the basic operations and functionality of a BST.

Uploaded by

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

//*Implementation of Binary Search Tree and its traversal methods_Diksha Gundap_19_CSD*//

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

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

struct Node* createNode(int value) {


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

struct Node* insert(struct Node* root, int


value) { if (root == NULL)
return createNode(value);

if (value < root->data)


root->left = insert(root->left,
value); else if (value > root-
>data)
root->right = insert(root->right, value);

return root;
}

void inorder(struct Node*


root) { if (root != NULL) {
inorder(root->left);
printf("%d ", root-
>data); inorder(root-
>right);
}
}

void preorder(struct Node*


root) { if (root != NULL) {
printf("%d ", root-
>data);
preorder(root->left);
preorder(root-
>right);
}
}

void postorder(struct Node*


root) { if (root != NULL) {
postorder(root->left);
postorder(root-
>right); printf("%d ",
root->data);
}
}

int main() {
struct Node* root = NULL;
int values[] = {20, 36, 80, 20, 40, 60, 55};
int n = sizeof(values) / sizeof(values[0]);
for (int i = 0; i < n; i++) {
root = insert(root, values[i]);
}

printf("Inorder Traversal: ");


inorder(root);
printf("\n");

printf("Preorder Traversal: ");


preorder(root);
printf("\n");

printf("Postorder Traversal: ");


postorder(root);
printf("\n");

return 0;
}

You might also like