![]() |
VOOZH | about |
We strongly recommend to refer below posts as a prerequisite of this.
K Dimensional Tree | Set 1 (Search and Insert)
K Dimensional Tree | Set 2 (Find Minimum)
In this post delete is discussed. The operation is to delete a given point from K D Tree.
Like Binary Search Tree Delete, we recursively traverse down and search for the point to be deleted. Below are steps are followed for every node visited.
1) If current node contains the point to be deleted
2) If current doesn't contain the point to be deleted
Why 1.b and 1.c are different from BST?
In BST delete, if a node's left child is empty and right is not empty, we replace the node with right child. In K D Tree, doing this would violate the KD tree property as dimension of right child of node is different from node's dimension. For example, if node divides point by x axis values. then its children divide by y axis, so we can't simply replace node with right child. Same is true for the case when right child is not empty and left child is empty.
Why 1.c doesn't find max in left subtree and recur for max like 1.b?
Doing this violates the property that all equal values are in right subtree. For example, if we delete (!0, 10) in below subtree and replace if with
Wrong Way (Equal key in left subtree after deletion) (5, 6) (4, 10) / Delete(5, 6) / (4, 10) ------------> (4, 20) \ (4, 20) Right way (Equal key in right subtree after deletion) (5, 6) (4, 10) / Delete(5, 6) \ (4, 10) ------------> (4, 20) \ (4, 20)
Example of Delete:
Delete (30, 40): Since right child is not NULL and dimension of node is x, we find the node with minimum x value in right child. The node is (35, 45), we replace (30, 40) with (35, 45) and delete (30, 40).
Delete (70, 70): Dimension of node is y. Since right child is NULL, we find the node with minimum y value in left child. The node is (50, 30), we replace (70, 70) with (50, 30) and recursively delete (50, 30) in left subtree. Finally we make the modified left subtree as right subtree of (50, 30).
Below is C++ implementation of K D Tree delete.
Root after deletion of (30, 40) 35, 45
The time complexity is O(log N), where N is the number of nodes in the KD-Tree. This is because the KD-Tree has a balanced structure with log N levels, and the insertion, deletion, and search operations traverse the tree in a way that reduces the search space by half at each level.
The space complexity is also O(N) since each node requires space for k integers (where k is the number of dimensions), as well as two pointers to child nodes, each of which requires a pointer-sized space. Additionally, the program uses recursive functions to traverse the tree, which adds to the stack space required, which is also O(N) in the worst case if the tree is unbalanced.
Source:
https://www.cs.umd.edu/class/spring2008/cmsc420/L19.kd-trees.pdf