Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
K2Tree< T > Class Template Reference

2D k-d tree for efficient spatial point operations. More...

#include <tpl_2dtree.H>

Collaboration diagram for K2Tree< T >:
[legend]

Classes

struct  NearestState
 Thread-local state for nearest-neighbor recursion. More...
 
struct  Node
 Internal node structure for the k-d tree. More...
 

Public Member Functions

 K2Tree ()
 Default constructor - creates an empty tree with zero-sized region.
 
 K2Tree (Point pmin, Point pmax)
 Construct a k-d tree with specified bounding region.
 
 K2Tree (const Geom_Number &xmin, const Geom_Number &ymin, const Geom_Number &xmax, const Geom_Number &ymax)
 Construct a k-d tree with specified coordinate bounds.
 
 K2Tree (const K2Tree &)=delete
 
K2Treeoperator= (const K2Tree &)=delete
 
 K2Tree (K2Tree &&other) noexcept
 Move constructor — transfers ownership of all nodes.
 
K2Treeoperator= (K2Tree &&other) noexcept
 Move assignment operator — transfers ownership of all nodes.
 
constexpr bool is_empty () const noexcept
 Check if the tree is empty.
 
constexpr size_t size () const noexcept
 Get the number of points in the tree.
 
bool insert (const Point &p)
 Insert a point into the tree.
 
bool contains (const Point &p) const noexcept
 Check if the tree contains a point.
 
void range (const Rectangle &rect, DynList< Point > *l) const
 Find all points within a rectangle.
 
std::optional< Pointnearest (const Point &p) const noexcept
 Find the nearest point to a query point.
 
template<typename Op >
void for_each (Op &&op) const
 Apply an operation to every point in the tree (inorder).
 
 ~K2Tree ()
 Destructor - frees all nodes.
 

Static Public Member Functions

static K2Tree build (Array< Point > points, const Point &pmin, const Point &pmax)
 Build a balanced k-d tree from an array of points.
 

Private Member Functions

Nodelr_insert (Node *root, const Point &p)
 Insert into tree with left-right (X) split.
 
Nodebu_insert (Node *root, const Point &p)
 Insert into tree with bottom-up (Y) split.
 
void destroy_tree (Node *node) noexcept
 Recursively delete all nodes.
 

Static Private Member Functions

static Nodebu_search (Node *root, const Point &p) noexcept
 Search with bottom-up (Y) split pattern.
 
static Nodelr_search (Node *root, const Point &p) noexcept
 Search with left-right (X) split pattern.
 
static void range (Node *root, const Rectangle &rect, DynList< Point > *q)
 Recursively find points within a rectangle.
 
static void lr_nearest (Node *root, const Point &p, NearestState &st) noexcept
 Recursively find the nearest neighbor (X-split level).
 
static void bu_nearest (Node *root, const Point &p, NearestState &st) noexcept
 Recursively find the nearest neighbor (Y-split level).
 
static Nodebuild_balanced (Array< Point > &pts, const size_t lo, const size_t hi, const bool split_x, const Point &rmin, const Point &rmax)
 Recursively build a balanced subtree selecting medians.
 
template<typename Op >
static void for_each_node (const Node *node, Op &&op)
 Recursive inorder traversal helper for for_each.
 

Private Attributes

Point pmin_
 Lower-left corner of reference rectangle.
 
Point pmax_
 Upper-right corner of reference rectangle.
 
size_t N_
 Number of points in the tree.
 
Noderoot_
 Root of the tree.
 

Detailed Description

template<typename T = Empty_Class>
class K2Tree< T >

2D k-d tree for efficient spatial point operations.

K2Tree is a binary space partitioning tree that recursively divides 2D space using alternating vertical (X) and horizontal (Y) splits. Each node represents a point and implicitly defines a rectangular region.

Key Characteristics:
  • Alternating splits: Even levels split on X, odd levels split on Y
  • Binary structure: Each node has at most two children (left/bottom, right/top)
  • Duplicate rejection: Duplicate points are not inserted
  • Balanced on random data: Expected O(log n) height for random insertions
  • Worst-case unbalanced: Can degenerate to O(n) on sorted data
Split Pattern:
Root (split on X):
y < child.y Bottom subtree
y >= child.y Top subtree
└─ ...
#define Y(p)
Definition btreepic.C:375
#define X(p)
Definition btreepic.C:374
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4060
static mpfr_t y
Definition mpfr_mul_d.c:3
Divide_Conquer_DP_Result< Cost > divide_and_conquer_partition_dp(const size_t groups, const size_t n, Transition_Cost_Fn transition_cost, const Cost inf=dp_optimization_detail::default_inf< Cost >())
Optimize partition DP using divide-and-conquer optimization.
std::vector< std::string > & split(const std::string &s, const char delim, std::vector< std::string > &elems)
Split a std::string by a single delimiter character.
Complexity:
  • Insert: O(log n) average, O(n) worst case
  • Search: O(log n) average, O(n) worst case
  • Nearest neighbor: O(log n) average, O(n) worst case
  • Range query: O(sqrt(n) + k) where k is result size
  • Space: O(n)
Comparison with QuadTree:
  • K2Tree: Binary splits, simpler structure, better for uniformly distributed data
  • QuadTree: Quaternary splits, adapts to density, better for clustered data
Use Cases:
✓ Nearest neighbor search ✓ Range queries (all points in rectangle) ✓ Spatial databases ✓ Computer graphics (ray tracing, collision detection) ✓ Geographic information systems (GIS)
Example:
// Create a k-d tree for region [0, 100] × [0, 100]
K2Tree<> tree(0, 0, 100, 100);
// Insert points
tree.insert(Point(25, 50));
tree.insert(Point(75, 25));
tree.insert(Point(50, 75));
// Check if point exists
if (tree.contains(Point(25, 50)))
std::cout << "Point found!" << '\n';
// Find nearest neighbor
if (auto nearest = tree.nearest(Point(30, 45)))
std::cout << "Nearest: (" << nearest->get_x() << ", "
<< nearest->get_y() << ")" << '\n';
// Range query
Rectangle rect(20, 20, 80, 80);
tree.range(rect, &points_in_rect);
Dynamic singly linked list with functional programming support.
Definition htlist.H:1155
Represents a point with rectangular coordinates in a 2D plane.
Definition point.H:229
An axis-aligned rectangle.
Definition point.H:1737
2D k-d tree for efficient spatial point operations.
Definition tpl_2dtree.H:136
std::optional< Point > nearest(const Point &p) const noexcept
Find the nearest point to a query point.
Definition tpl_2dtree.H:557
Template Parameters
TOptional user data type associated with points (default: Empty_Class)
Note
The tree does NOT automatically balance. For sorted insertions, use the static build() factory which selects medians to produce an O(log n)-height tree.
See also
QuadTree Alternative spatial structure with adaptive quadrant subdivision.
Author
Leandro Rabindranath León

Definition at line 135 of file tpl_2dtree.H.

Constructor & Destructor Documentation

◆ K2Tree() [1/5]

template<typename T = Empty_Class>
K2Tree< T >::K2Tree ( )
inline

Default constructor - creates an empty tree with zero-sized region.

Definition at line 180 of file tpl_2dtree.H.

◆ K2Tree() [2/5]

template<typename T = Empty_Class>
K2Tree< T >::K2Tree ( Point  pmin,
Point  pmax 
)
inline

Construct a k-d tree with specified bounding region.

Parameters
pminLower-left corner of the region
pmaxUpper-right corner of the region

Definition at line 190 of file tpl_2dtree.H.

◆ K2Tree() [3/5]

template<typename T = Empty_Class>
K2Tree< T >::K2Tree ( const Geom_Number xmin,
const Geom_Number ymin,
const Geom_Number xmax,
const Geom_Number ymax 
)
inline

Construct a k-d tree with specified coordinate bounds.

Parameters
xminMinimum X coordinate
yminMinimum Y coordinate
xmaxMaximum X coordinate
ymaxMaximum Y coordinate

Definition at line 203 of file tpl_2dtree.H.

◆ K2Tree() [4/5]

template<typename T = Empty_Class>
K2Tree< T >::K2Tree ( const K2Tree< T > &  )
delete

◆ K2Tree() [5/5]

template<typename T = Empty_Class>
K2Tree< T >::K2Tree ( K2Tree< T > &&  other)
inlinenoexcept

Move constructor — transfers ownership of all nodes.

Definition at line 215 of file tpl_2dtree.H.

References Aleph::divide_and_conquer_partition_dp().

◆ ~K2Tree()

template<typename T = Empty_Class>
K2Tree< T >::~K2Tree ( )
inline

Destructor - frees all nodes.

Definition at line 738 of file tpl_2dtree.H.

References K2Tree< T >::destroy_tree(), and K2Tree< T >::root_.

Member Function Documentation

◆ bu_insert()

template<typename T = Empty_Class>
Node * K2Tree< T >::bu_insert ( Node root,
const Point p 
)
inlineprivate

Insert into tree with bottom-up (Y) split.

Recursively inserts a point, splitting on Y coordinate at this level.

Parameters
rootCurrent node
pPoint to insert
Returns
New subtree root, or nullptr if point is duplicate

Definition at line 313 of file tpl_2dtree.H.

References Aleph::divide_and_conquer_partition_dp(), Aleph::Point::get_x(), Aleph::Point::get_y(), K2Tree< T >::lr_insert(), and root().

Referenced by K2Tree< T >::lr_insert().

◆ bu_nearest()

template<typename T = Empty_Class>
static void K2Tree< T >::bu_nearest ( Node root,
const Point p,
NearestState st 
)
inlinestaticprivatenoexcept

Recursively find the nearest neighbor (Y-split level).

Parameters
rootCurrent node
pQuery point
stMutable search state

Definition at line 521 of file tpl_2dtree.H.

References K2Tree< T >::lr_nearest(), and root().

Referenced by K2Tree< T >::lr_nearest().

◆ bu_search()

template<typename T = Empty_Class>
static Node * K2Tree< T >::bu_search ( Node root,
const Point p 
)
inlinestaticprivatenoexcept

Search with bottom-up (Y) split pattern.

Definition at line 391 of file tpl_2dtree.H.

References K2Tree< T >::lr_search(), and root().

Referenced by K2Tree< T >::lr_search().

◆ build()

template<typename T = Empty_Class>
static K2Tree K2Tree< T >::build ( Array< Point points,
const Point pmin,
const Point pmax 
)
inlinestatic

Build a balanced k-d tree from an array of points.

Constructs a balanced tree by recursively selecting medians, alternating between X and Y coordinates. This avoids the degeneration to O(n) height that occurs with sorted insertions.

Duplicate points are removed internally.

Parameters
pointsArray of points (copied internally).
pminLower-left corner of the bounding region.
pmaxUpper-right corner of the bounding region.
Returns
A balanced K2Tree containing all unique points.
Complexity:
  • Time: O(n log n)
  • Space: O(n)

Definition at line 599 of file tpl_2dtree.H.

References K2Tree< T >::build_balanced(), Aleph::Point::get_x(), Aleph::Point::get_y(), Aleph::in_place_sort(), Aleph::Array< T >::is_empty(), K2Tree< T >::N_, Aleph::pmax(), Aleph::pmin(), r, Aleph::Array< T >::remove_last(), K2Tree< T >::root_, Aleph::Array< T >::size(), and w.

Referenced by Aleph::KDTreePointSearch::build(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), and TEST().

◆ build_balanced()

template<typename T = Empty_Class>
static Node * K2Tree< T >::build_balanced ( Array< Point > &  pts,
const size_t  lo,
const size_t  hi,
const bool  split_x,
const Point rmin,
const Point rmax 
)
inlinestaticprivate

Recursively build a balanced subtree selecting medians.

After nth_element, elements with the same splitting coordinate as the median are moved to the right partition so that lr_search/bu_search (which send equal-coord queries right) can find them.

Definition at line 639 of file tpl_2dtree.H.

References K2Tree< T >::build_balanced(), Aleph::divide_and_conquer_partition_dp(), Aleph::Point::get_x(), Aleph::Point::get_y(), K2Tree< T >::Node::lb_, K2Tree< T >::Node::rt_, K2Tree< T >::Node::set_rect(), K2Tree< T >::Node::x(), and K2Tree< T >::Node::y().

Referenced by K2Tree< T >::build(), and K2Tree< T >::build_balanced().

◆ contains()

template<typename T = Empty_Class>
bool K2Tree< T >::contains ( const Point p) const
inlinenoexcept

Check if the tree contains a point.

Definition at line 430 of file tpl_2dtree.H.

References K2Tree< T >::lr_search(), and K2Tree< T >::root_.

Referenced by Aleph::KDTreePointSearch::contains(), main(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), and TEST().

◆ destroy_tree()

template<typename T = Empty_Class>
void K2Tree< T >::destroy_tree ( Node node)
inlineprivatenoexcept

Recursively delete all nodes.

Definition at line 726 of file tpl_2dtree.H.

References K2Tree< T >::destroy_tree().

Referenced by K2Tree< T >::~K2Tree(), K2Tree< T >::destroy_tree(), and K2Tree< T >::operator=().

◆ for_each()

template<typename T = Empty_Class>
template<typename Op >
void K2Tree< T >::for_each ( Op &&  op) const
inline

Apply an operation to every point in the tree (inorder).

Template Parameters
OpCallable with signature compatible with void(const Point &).
Parameters
opThe operation to apply.

Definition at line 577 of file tpl_2dtree.H.

References K2Tree< T >::for_each_node(), and K2Tree< T >::root_.

Referenced by Aleph::KDTreePointSearch::for_each(), TEST(), and TEST().

◆ for_each_node()

template<typename T = Empty_Class>
template<typename Op >
static void K2Tree< T >::for_each_node ( const Node node,
Op &&  op 
)
inlinestaticprivate

Recursive inorder traversal helper for for_each.

Definition at line 715 of file tpl_2dtree.H.

References K2Tree< T >::for_each_node(), K2Tree< T >::Node::lb_, K2Tree< T >::Node::point_, and K2Tree< T >::Node::rt_.

Referenced by K2Tree< T >::for_each(), and K2Tree< T >::for_each_node().

◆ insert()

template<typename T = Empty_Class>
bool K2Tree< T >::insert ( const Point p)
inline

Insert a point into the tree.

The point is inserted only if it's not already present (no duplicates).

Parameters
pPoint to insert.
Returns
true if the point was inserted, false if it was a duplicate.

Definition at line 371 of file tpl_2dtree.H.

References Aleph::divide_and_conquer_partition_dp(), K2Tree< T >::lr_insert(), K2Tree< T >::N_, K2Tree< T >::pmax_, K2Tree< T >::pmin_, K2Tree< T >::root_, and K2Tree< T >::Node::set_rect().

Referenced by Aleph::KDTreePointSearch::insert(), main(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), and TEST().

◆ is_empty()

template<typename T = Empty_Class>
constexpr bool K2Tree< T >::is_empty ( ) const
inlineconstexprnoexcept

Check if the tree is empty.

Definition at line 240 of file tpl_2dtree.H.

References K2Tree< T >::N_.

Referenced by Aleph::KDTreePointSearch::is_empty(), TEST(), TEST(), TEST(), TEST(), and TEST().

◆ lr_insert()

template<typename T = Empty_Class>
Node * K2Tree< T >::lr_insert ( Node root,
const Point p 
)
inlineprivate

Insert into tree with left-right (X) split.

Recursively inserts a point, splitting on X coordinate at this level.

Parameters
rootCurrent node
pPoint to insert
Returns
New subtree root, or nullptr if point is duplicate

Definition at line 254 of file tpl_2dtree.H.

References K2Tree< T >::bu_insert(), Aleph::divide_and_conquer_partition_dp(), Aleph::Point::get_x(), Aleph::Point::get_y(), and root().

Referenced by K2Tree< T >::bu_insert(), and K2Tree< T >::insert().

◆ lr_nearest()

template<typename T = Empty_Class>
static void K2Tree< T >::lr_nearest ( Node root,
const Point p,
NearestState st 
)
inlinestaticprivatenoexcept

Recursively find the nearest neighbor (X-split level).

Parameters
rootCurrent node
pQuery point
stMutable search state

Definition at line 488 of file tpl_2dtree.H.

References K2Tree< T >::bu_nearest(), and root().

Referenced by K2Tree< T >::bu_nearest(), and K2Tree< T >::nearest().

◆ lr_search()

template<typename T = Empty_Class>
static Node * K2Tree< T >::lr_search ( Node root,
const Point p 
)
inlinestaticprivatenoexcept

Search with left-right (X) split pattern.

Definition at line 410 of file tpl_2dtree.H.

References K2Tree< T >::bu_search(), and root().

Referenced by K2Tree< T >::bu_search(), and K2Tree< T >::contains().

◆ nearest()

template<typename T = Empty_Class>
std::optional< Point > K2Tree< T >::nearest ( const Point p) const
inlinenoexcept

Find the nearest point to a query point.

Performs a nearest neighbor search using branch-and-bound pruning. This method is const and thread-safe (no mutable members).

Parameters
pQuery point
Returns
The nearest point in the tree; empty if the tree is empty.

Definition at line 557 of file tpl_2dtree.H.

References K2Tree< T >::NearestState::dist2, Aleph::Point::distance_squared_to(), K2Tree< T >::lr_nearest(), K2Tree< T >::N_, K2Tree< T >::NearestState::node, K2Tree< T >::Node::point_, and K2Tree< T >::root_.

Referenced by main(), Aleph::KDTreePointSearch::nearest(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), and TEST().

◆ operator=() [1/2]

template<typename T = Empty_Class>
K2Tree & K2Tree< T >::operator= ( const K2Tree< T > &  )
delete

◆ operator=() [2/2]

template<typename T = Empty_Class>
K2Tree & K2Tree< T >::operator= ( K2Tree< T > &&  other)
inlinenoexcept

Move assignment operator — transfers ownership of all nodes.

Definition at line 224 of file tpl_2dtree.H.

References K2Tree< T >::destroy_tree(), Aleph::divide_and_conquer_partition_dp(), K2Tree< T >::N_, K2Tree< T >::pmax_, K2Tree< T >::pmin_, and K2Tree< T >::root_.

◆ range() [1/2]

template<typename T = Empty_Class>
void K2Tree< T >::range ( const Rectangle rect,
DynList< Point > *  l 
) const
inline

Find all points within a rectangle.

Performs a range query to find all points that lie within the specified rectangle.

Parameters
rectQuery rectangle
lOutput list where matching points are appended

Definition at line 466 of file tpl_2dtree.H.

References Aleph::divide_and_conquer_partition_dp(), l, K2Tree< T >::N_, K2Tree< T >::range(), and K2Tree< T >::root_.

◆ range() [2/2]

template<typename T = Empty_Class>
static void K2Tree< T >::range ( Node root,
const Rectangle rect,
DynList< Point > *  q 
)
inlinestaticprivate

Recursively find points within a rectangle.

Parameters
rootCurrent node
rectQuery rectangle
qOutput list for matching points

Definition at line 442 of file tpl_2dtree.H.

References Aleph::DynList< T >::append(), Aleph::divide_and_conquer_partition_dp(), K2Tree< T >::range(), and root().

Referenced by main(), Aleph::KDTreePointSearch::range(), K2Tree< T >::range(), K2Tree< T >::range(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), and TEST().

◆ size()

template<typename T = Empty_Class>
constexpr size_t K2Tree< T >::size ( ) const
inlineconstexprnoexcept

Get the number of points in the tree.

Definition at line 243 of file tpl_2dtree.H.

References K2Tree< T >::N_.

Referenced by Aleph::KDTreePointSearch::size(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), TEST(), and TEST().

Member Data Documentation

◆ N_

template<typename T = Empty_Class>
size_t K2Tree< T >::N_
private

◆ pmax_

template<typename T = Empty_Class>
Point K2Tree< T >::pmax_
private

Upper-right corner of reference rectangle.

Definition at line 174 of file tpl_2dtree.H.

Referenced by K2Tree< T >::insert(), and K2Tree< T >::operator=().

◆ pmin_

template<typename T = Empty_Class>
Point K2Tree< T >::pmin_
private

Lower-left corner of reference rectangle.

Definition at line 173 of file tpl_2dtree.H.

Referenced by K2Tree< T >::insert(), and K2Tree< T >::operator=().

◆ root_


The documentation for this class was generated from the following file: