-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearching_BST.cpp
75 lines (68 loc) · 1.32 KB
/
searching_BST.cpp
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
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
};
Node *newNode(int data)
{
Node *node = new Node;
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
Node *insertLevelOrder(int arr[], int i, int n)
{
Node *root = nullptr;
if (i < n)
{
root = newNode(arr[i]);
root->left = insertLevelOrder(arr, 2 * i + 1, n);
root->right = insertLevelOrder(arr, 2 * i + 2, n);
}
return root;
}
void inorder_traversal(Node *root)
{
if (root != NULL)
{
inorder_traversal(root->left);
cout << root->data << " ";
inorder_traversal(root->right);
}
}
void search_bst(Node *node, int e)
{
if (node != nullptr)
{
if (node->data == e)
{
cout << "found";
return;
}
if (node->data > e)
{
return search_bst(node->left, e);
}
else
{
return search_bst(node->right, e);
}
}
else
{
cout << "Element is not present in tree.";
}
}
int main()
{
int arr[] = {30, 20, 40, 10, 25, 35, 50};
int n = sizeof(arr) / sizeof(arr[0]);
Node *root = insertLevelOrder(arr, 0, n);
// inorder_traversal(root);
search_bst(root, 1);
return 0;
}