K Dimensional Tree | Set 3 (Delete)
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
- If node to be deleted is a leaf node, simply delete it (Same as BST Delete)
- If node to be deleted has right child as not NULL (Different from BST)
- Find minimum of current node’s dimension in right subtree.
- Replace the node with above found minimum and recursively delete minimum in right subtree.
- Else If node to be deleted has left child as not NULL (Different from BST)
- Find minimum of current node’s dimension in left subtree.
- Replace the node with above found minimum and recursively delete minimum in left subtree.
- Make new left subtree as right child of current node.
2) If current doesn’t contain the point to be deleted
- If node to be deleted is smaller than current node on current dimension, recur for left subtree.
- Else recur for right subtree.
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.






.png)
