Il 0% ha trovato utile questo documento (0 voti)
2 visualizzazioni3 pagine

Ex 4

Coding for c++data structure

Caricato da

jincyyoshlin
Copyright
© © All Rights Reserved
Per noi i diritti sui contenuti sono una cosa seria. Se sospetti che questo contenuto sia tuo, rivendicalo qui.
Formati disponibili
Scarica in formato PDF, TXT o leggi online su Scribd
Il 0% ha trovato utile questo documento (0 voti)
2 visualizzazioni3 pagine

Ex 4

Coding for c++data structure

Caricato da

jincyyoshlin
Copyright
© © All Rights Reserved
Per noi i diritti sui contenuti sono una cosa seria. Se sospetti che questo contenuto sia tuo, rivendicalo qui.
Formati disponibili
Scarica in formato PDF, TXT o leggi online su Scribd
Sei sulla pagina 1/ 3

4.

Binary search tree


#include <stdio.h>
#include <stdlib.h>
// Structure for a tree node
struct Node {
int data;
struct Node *left;
struct Node *right;
};
// Function to create a new node
struct Node *createNode(int value) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Function to insert a node into BST
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;
}
// Function to traverse the tree in inorder
void inorder(struct Node *root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
void main() {
int i,n, value;
struct Node *root = NULL;
clrscr();
printf("\nBinary Search Tree\n");
printf("----------------------\n");
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &value);
root = insert(root, value);
}
printf("Inorder traversal of the constructed BST:\n");
inorder(root);
printf("\n");
getch();
}
Output:

Potrebbero piacerti anche