-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkd.cpp
More file actions
106 lines (71 loc) · 1.85 KB
/
Copy pathkd.cpp
File metadata and controls
106 lines (71 loc) · 1.85 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include<bits/stdc++.h>
using namespace std;
const int k = 2;
struct Node
{
int point[k];
Node *left, *right;
};
struct Node* newNode(int arr[])
{
struct Node* temp = new Node;
for (int i=0; i<k; i++)
temp->point[i] = arr[i];
temp->left = temp->right = NULL;
return temp;
}
Node *insertRec(Node *root, int point[], unsigned depth)
{
// Tree is empty?
if (root == NULL)
return newNode(point);
unsigned cd = depth % k;
if (point[cd] < (root->point[cd]))
root->left = insertRec(root->left, point, depth + 1);
else
root->right = insertRec(root->right, point, depth + 1);
return root;
}
Node* insert(Node *root, int point[])
{
return insertRec(root, point, 0);
}
bool arePointsSame(int point1[], int point2[])
{
for (int i = 0; i < k; ++i)
if (point1[i] != point2[i])
return false;
return true;
}
bool searchRec(Node* root, int point[], unsigned depth)
{
if (root == NULL)
return false;
if (arePointsSame(root->point, point))
return true;
unsigned cd = depth % k;
if (point[cd] < root->point[cd])
return searchRec(root->left, point, depth + 1);
return searchRec(root->right, point, depth + 1);
}
bool search(Node* root, int point[])
{
return searchRec(root, point, 0);
}
int main()
{
struct Node *root = NULL;
cout <<"Enter no. of points to insert";
int n;
cin >> n;int point[2];
for (int i=0; i<n; i++)
{
int a,b;
cin >> point[0] >> point[1];
root = insert(root, point);
}
cout << "Enter the point to search";
cin >> point[0] >> point[1];
(search(root, point))? cout << "Found\n": cout << "Not Found\n";
return 0;
}