### Lookup, Insert and Delete Operations on a kd-tree

• Lookup a search key

• Lookup Algorithm:

 ``` Record lookup( x ) { n = root node; // Start at the root /* ======================================== Traverse internal nodes to reach a leaf ======================================== */ while ( n ≠ leaf node ) { n is indexed using component i; if ( x.compi < n.key ) n = n.left; else n = n.right; } /* ============================ We have reached a leaf node ============================ */ if ( x ∈ n (leaf node) ) { return Record for x } else { return No Found; } } ```

Example: lookup age = 35 and salary = 500K

• Insert Algorithm

• Insert Algorithm for the kd-tree:

 ``` insert ( Record x ) { Use the search key in x to find: the leaf node L that will hold x if ( L has space store store x ) { insert record x in (block) L; } else { Let i = search dimension in parent node of L Let j = the next dimension after i /* ========================================= Split the leaf node L in dimension j ========================================= */ K = the median of search key values in dimension j; Move all records with key < K into block L1; Move all records with key >= K into block L2; Replace L by an internal node with key K; Set: K.left = L1; K.right = L2; } } ```

• Example:

• Insert the record for a person with age = 35 and salary = 500K into the following kd-tree:

• Search for the leaf node that holds age = 35, salary = 500K:

• This level must use age to make a branch decision.

Therefore:

• Find the median of the age value in the data records:

 ``` 25 400 35 500 <---- Median 45 350 ```

• Use the median value = 35 to split the records

Result:

• Delete a record from a kd-tree

• Delete

• The delete operation is very complex and require many block accesses

(If you remember the delete algorithm in Binary Search Tree you will understand --- you may need to replace the deleted record by its successor)

• Work-around::

• Instead of actually deleting the record:

 We mark the record as deleted (tomb stone record)

• From time to time, the system rebuild the kd-tree from scratch to remove the deleted records.