Step 4 is the “else” in step 3, what do you do if the plane is closer than the point. Just because the point you find will be in the same rectangle as the point you find for the neighbor does not mean that it is closest.
Imagine the following scenario: you have two points in your kD-tree, A and B. A is in the middle of its rectangle, and B is just above the edge, in the area with the section next to A. If you are now looking for the nearest neighbor to the point C, which is next to B, but turns out to be the other side of the edge, and in the area of ​​section A, your first point you choose will be A because of the initial depth of the first search, which selects everything that will be in the same section as your search point. However, B is really closer, therefore, even if you chose A, you need to check if B is closer, otherwise your kD-tree will not actually give you the correct results.
A good way to visualize this is to cross out it:
a ------------- C-- | -IN
A is the first point we found in DFS, C is our point we want to find the nearest neighbor, B is the nearest nearest neighbor, | is our splitting plane.
Another way to think about it is to draw a circle with a radius dist (A, C) around point C. If any other rectangles have any part of themselves, fall into this circle, then there is a chance that they hold a point that may be closer to C than A, so they need to be checked. If you now find B, you can reduce the radius of your circle (because B is closer) so that fewer rectangles are able to intersect, and as soon as you check all the rectangles that intersect with your circle (decreasing the radius of the circle as your find closer neighbors) , you can finally say that there are no nearby points.
source share