-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch a node in BST
85 lines (64 loc) · 1.49 KB
/
Search a node in BST
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
// Initial Template for C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node {
int data;
struct Node *right;
struct Node *left;
};
struct Node *createNewNode(int value) {
struct Node *temp = (struct Node *)malloc(sizeof(struct Node *));
temp->data = value;
temp->left = temp->right = NULL;
return temp;
}
struct Node *insert(struct Node *tree, int val) {
if (tree == NULL) {
return createNewNode(val);
}
if (val < tree->data) {
tree->left = insert(tree->left, val);
} else if (val > tree->data) {
tree->right = insert(tree->right, val);
}
return tree;
}
// } Driver Code Ends
// User function Template for C
// Function to search a struct node in BST.
bool search(struct Node* root, int x) {
if(root==NULL)
return 0;
if(root->data==x)
return root;
if(root->data>x)
return search(root->left,x);
if(root->data<x)
return search(root->right,x);
}
// { Driver Code Starts.
int main() {
int T;
scanf("%d", &T);
while (T--) {
struct Node *root = NULL;
int N;
scanf("%d", &N);
for (int i = 0; i < N; i++) {
int k;
scanf("%d", &k);
root = insert(root, k);
}
int s;
scanf("%d", &s);
bool ans = search(root, s);
if (ans) {
printf("1\n");
} else {
printf("0\n");
}
}
return 0;
}
// } Driver Code Ends