Repository navigation
Expand file tree
/
Copy pathBinary Search Tree
More file actions
85 lines (72 loc) · 1.99 KB
/
Copy pathBinary Search Tree
File metadata and controls
85 lines (72 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a node in the tree
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
// Function to create a new node
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Function to insert a new node into the BST
Node* insertNode(Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);
} else if (data > root->data) {
root->right = insertNode(root->right, data);
}
return root;
}
// Function to search for a value in the BST
Node* searchNode(Node* root, int data) {
if (root == NULL || root->data == data) {
return root;
}
if (data < root->data) {
return searchNode(root->left, data);
} else {
return searchNode(root->right, data);
}
}
// Function for in-order traversal of the BST
void inOrderTraversal(Node* root) {
if (root != NULL) {
inOrderTraversal(root->left);
printf("%d ", root->data);
inOrderTraversal(root->right);
}
}
// Main function to demonstrate the BST operations
int main() {
Node* root = NULL;
// Insert values into the BST
root = insertNode(root, 50);
insertNode(root, 30);
insertNode(root, 20);
insertNode(root, 40);
insertNode(root, 70);
insertNode(root, 60);
insertNode(root, 80);
// Print the in-order traversal of the BST
printf("In-order traversal of the BST:\n");
inOrderTraversal(root);
printf("\n");
// Search for a value in the BST
int searchValue = 40;
Node* result = searchNode(root, searchValue);
if (result != NULL) {
printf("Value %d found in the BST.\n", searchValue);
} else {
printf("Value %d not found in the BST.\n", searchValue);
}
return 0;
}