概述
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define BinNodePos BinNode*
typedef struct Point{//二维坐标类
int x;
int y;
Point() { x = 0; y = 0; }
Point(int xx, int yy) :x(xx), y(yy) {};
};
bool cmp(Point &a, Point &b) {//比较函数,用于为坐标排序
return (a.x != b.x) ? a.x < b.x : a.y < b.y;
}
class BinNode {//二叉树节点
public:
int x;
BinNodePos pr;
BinNodePos lc;
BinNodePos rc;
vector<int> y;//range tree 的每一个节点都是x坐标相同的节点的集合,y节点储存在向量内
BinNode(int _x) {
x = _x;
pr = NULL;
lc = NULL;
rc = NULL;
}
};
class AVL {
public:
BinNodePos root;
int size;
AVL() {
root = NULL;
size = 0;
}
BinNodePos cstX(vector<BinNodePos> x, BinNodePos prt, int lo, int hi) {//使用已排序的节点,二分递归创建二叉平衡树
if (hi - lo == 1) return x[lo];
if (hi == lo) return NULL;
int mi = (lo + hi) / 2;
BinNodePos bn = x[mi];
bn->pr = prt;
bn->lc = cstX(x, bn, lo, mi);
bn->rc = cstX(x, bn, mi + 1, hi);
return bn;
}
void print(Point *pt, int n) {//打印
for (int i = 0; i < n; i++) {
cout << "(" << pt[i].x << "," << pt[i].y << ")" << " ";
}
cout << endl;
}
void construct(Point *pt,int n) {//创建二叉平衡树
sort(pt, pt + n, cmp);//现将所有的点排序
print(pt, n);
vector<BinNodePos> xNode;//x节点相同,y节点不同的二叉树节点集合
int x = pt[0].x;
BinNodePos b = new BinNode(x);//当前节点
b->y.push_back(pt[0].y);
for (int i = 1; i < n; i++) {
if (x == pt[i].x) {//如果相同,直接将y值加进去
b->y.push_back(pt[i].y);
}
else {//不是,则将当前节点加入集合,然后再创建一个
x = pt[i].x;
xNode.push_back(b);
b = new BinNode(x);
b->y.push_back(pt[i].y);
}
}
if (xNode[xNode.size() - 1]->x != b->x) xNode.push_back(b);//处理最后一个节点
size = xNode.size();
root = cstX(xNode, NULL, 0, xNode.size());//将处理好的二叉树节点递归建树
}
void visit(BinNodePos x) {
for (int i = 0; i < x->y.size(); i++) {
cout << "(" << x->x << "," << x->y[i] << ")"<<" ";
}
}
void search(BinNodePos x, Point a, Point b) {//中序递归范围搜索
if (x == NULL) return;
if (x->x > a.x) search(x->lc, a, b);
if (x->x <= b.x && x->x >= a.x) {
for (int i = 0; i < x->y.size(); i++) {
if(x->y[i]<=b.y&&x->y[i]>=a.y) cout<< "(" << x->x << "," << x->y[i] << ")" << " ";
}
cout << endl;
}
if (x->x < b.x) search(x->rc, a, b);
}
void traverse_mid(BinNodePos x) {//中序递归
if (x == NULL) return;
traverse_mid(x->lc);
visit(x);
traverse_mid(x->rc);
}
};
int main() {
Point *pt;
int n;
while (cin >> n) {
pt = new Point[n];
for (int i = 0; i < n; i++) {
cin >> pt[i].x >> pt[i].y;
}
cout << endl;
AVL avl;
avl.construct(pt, n);
avl.traverse_mid(avl.root);
avl.search(avl.root, Point(0, 2), Point(3, 4));
}
}
最后
以上就是大力大树为你收集整理的range tree范围树的全部内容,希望文章能够帮你解决range tree范围树所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复