A binary search tree (BST) is a data structure that stores elements in a binary tree, where each node has at most two children and satisfies the BST property: for each node, all nodes in its left subtree have keys less than the node’s key, and all nodes in its right subtree have keys greater than the node’s key. This property allows for efficient searching, insertion, and deletion of elements.
A map or dictionary is a data structure that stores key-value pairs and allows for efficient retrieval, insertion, and deletion of elements based on their keys. One way to implement a map or dictionary data structure is to use a binary search tree, where the keys are stored in the tree nodes and the values are stored as the values of the tree nodes.
Here is an example implementation of a BST-based map in Java:
public class BSTMap<K extends Comparable<K>, V> {
private Node root;
private class Node {
K key;
V value;
Node left;
Node right;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
}
public void put(K key, V value) {
root = put(root, key, value);
}
private Node put(Node node, K key, V value) {
if (node == null) {
return new Node(key, value);
}
int cmp = key.compareTo(node.key);
if (cmp < 0) {
node.left = put(node.left, key, value);
} else if (cmp > 0) {
node.right = put(node.right, key, value);
} else {
node.value = value;
}
return node;
}
public V get(K key) {
Node node = get(root, key);
return node == null ? null : node.value;
}
private Node get(Node node, K key) {
if (node == null) {
return null;
}
int cmp = key.compareTo(node.key);
if (cmp < 0) {
return get(node.left, key);
} else if (cmp > 0) {
return get(node.right, key);
} else {
return node;
}
}
public void delete(K key) {
root = delete(root, key);
}
private Node delete(Node node, K key) {
if (node == null) {
return null;
}
int cmp = key.compareTo(node.key);
if (cmp < 0) {
node.left = delete(node.left, key);
} else if (cmp > 0) {
node.right = delete(node.right, key);
} else {
if (node.left == null) {
return node.right;
} else if (node.right == null) {
return node.left;
} else {
Node min = min(node.right);
min.right = deleteMin(node.right);
min.left = node.left;
node = min;
}
}
return node;
}
private Node min(Node node) {
if (node.left == null) {
return node;
}
return min(node.left);
}
private Node deleteMin(Node node) {
if (node.left == null) {
return node.right;
}
node.left = deleteMin(node.left);
return node;
}
}
In this implementation, the BSTMap class uses a nested Node class to represent the nodes of the binary search tree. The put method inserts a key-value pair into the tree by recursively searching for the appropriate position to insert the node based on the key.