Skip to content

Commit 0945dbc

Browse files
authored
Add files via upload
1 parent 089080c commit 0945dbc

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

binary-space-partitioning.cpp

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// Language: cpp
2+
// Path: Tree/binary-space-partitioning.cpp
3+
// Implementation of the binary space partitioning tree.
4+
5+
#include <bits/stdc++.h>
6+
using namespace std;
7+
8+
// A node of the tree.
9+
struct Node {
10+
int x, y;
11+
Node *left, *right;
12+
Node(int x, int y) : x(x), y(y), left(NULL), right(NULL) {}
13+
};
14+
15+
// A comparator for sorting the points by x-coordinate.
16+
struct XComparator {
17+
bool operator()(const Node *a, const Node *b) {
18+
return a->x < b->x;
19+
}
20+
};
21+
22+
// A comparator for sorting the points by y-coordinate.
23+
struct YComparator {
24+
bool operator()(const Node *a, const Node *b) {
25+
return a->y < b->y;
26+
}
27+
};
28+
29+
// Builds a binary space partitioning tree for the given points.
30+
Node *build(vector<Node *> &points, int depth) {
31+
if (points.empty()) return NULL;
32+
if (points.size() == 1) return points[0];
33+
if (depth % 2 == 0) {
34+
sort(points.begin(), points.end(), XComparator());
35+
} else {
36+
sort(points.begin(), points.end(), YComparator());
37+
}
38+
int mid = points.size() / 2;
39+
Node *node = points[mid];
40+
vector<Node *> left(points.begin(), points.begin() + mid);
41+
vector<Node *> right(points.begin() + mid + 1, points.end());
42+
node->left = build(left, depth + 1);
43+
node->right = build(right, depth + 1);
44+
return node;
45+
}
46+
47+
// Prints the tree in the inorder traversal order.
48+
void print(Node *node) {
49+
if (node == NULL) return;
50+
print(node->left);
51+
printf("(%d, %d), ", node->x, node->y);
52+
print(node->right);
53+
}
54+
55+
int main() {
56+
vector<Node *> points;
57+
points.push_back(new Node(2, 3));
58+
points.push_back(new Node(5, 4));
59+
points.push_back(new Node(9, 6));
60+
points.push_back(new Node(4, 7));
61+
points.push_back(new Node(8, 1));
62+
points.push_back(new Node(4, 2));
63+
Node *root = build(points, 0);
64+
print(root);
65+
return 0;
66+
}

0 commit comments

Comments
 (0)