-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST.c
More file actions
74 lines (63 loc) · 1.67 KB
/
Copy pathBST.c
File metadata and controls
74 lines (63 loc) · 1.67 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
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
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;
}
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;
}
struct Node* search(struct Node* root, int value) {
if (root == NULL || root->data == value) {
return root;
}
if (value < root->data) {
return search(root->left, value);
}
return search(root->right, value);
}
void inorderTraversal(struct Node* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}
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("Inorder traversal of the BST: ");
inorderTraversal(root);
printf("\n");
int searchValue = 40;
struct Node* searchResult = search(root, searchValue);
if (searchResult != NULL) {
printf("%d is found in the BST.\n", searchValue);
} else {
printf("%d is not found in the BST.\n", searchValue);
}
return 0;
}