-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathBST.cpp
More file actions
executable file
·70 lines (60 loc) · 1.16 KB
/
BST.cpp
File metadata and controls
executable file
·70 lines (60 loc) · 1.16 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
#include<iostream>
using namespace std;
struct BST {
int val;
struct BST *left , *right;
};
BST* create(int val)
{
BST *node = new BST;
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
void insert(BST **root, int val)
{
while(*root != NULL) {
if((*root)->val < val)
root = &((* root)->left);
else
root = &((* root)->right);
}
*root = create(val);
}
void list(BST *root)
{
if(root != NULL) {
list(root->right);
cout << root->val << " ";
list(root->left);
}
}
int find(BST **root, int val)
{
int tval;
while(*root != NULL) {
tval = (* root)->val;
if(tval < val)
root = &((* root)->left);
else if(tval > val)
root = &((* root)->right);
else
return 1;
}
return 0;
}
int main()
{
BST *tree = new BST;
tree = NULL;
insert(&tree, 1);
insert(&tree, 4);
insert(&tree, 10);insert(&tree, 20);
list(tree);
cout << "Searching " << endl;
printf("%d ", find(&tree, 10));
printf("%d ", find(&tree, 20));
printf("%d ", find(&tree, 7));
return 0;
}