Consider the following TypeScript code, which demonstrates storing key-value pairs using arrays. To manage these pairs, we will initialize the BinarySearchTree with a custom comparison function:
import { BinarySearchTree } from '@datastructures-js/binary-search-tree';
const entries: [string, number][] = [['banana', 3], ['apple', 4], ['pear', 1], ['orange', 2]];
const compareArrays = (a: [string, number], b: [string, number]) => a[0].localeCompare(b[0]);
const bst = new BinarySearchTree(compareArrays);
entries.forEach(entry => bst.insert(entry));
const valueNode = bst.find(['apple', 0]);
console.log('Value:', valueNode ? valueNode.getValue()[1] : 'Not found');
// Output: Value: 4
const lowerBound = bst.lowerBound(['apple', 0], false);
console.log('Exclusive lower bound for apple:', lowerBound ? lowerBound.getValue() : 'Not found');
// Output: Exclusive lower bound for apple: Not found
const upperBound = bst.upperBound(['apple', 0], false);
console.log('Exclusive upper bound for apple:', upperBound ? upperBound.getValue() : 'Not found');
// Output: Exclusive upper bound for apple: [ 'banana', 3 ]
const minItem = bst.min();
console.log('Min item:', minItem ? minItem.getValue() : 'Tree is empty');
// Output: Min item: [ 'apple', 4 ]
const maxItem = bst.max();
console.log('Max item:', maxItem ? maxItem.getValue() : 'Tree is empty');
// Output: Max item: [ 'pear', 1 ]
In this example, we pass a custom comparison function compareArrays to the BinarySearchTree constructor. This function takes two arguments, a and b, which are arrays representing key-value pairs. The function compares the first elements of these arrays (the keys) using localeCompare to ensure the tree is sorted based on the keys in lexicographical order.
In the lowerBound and upperBound methods, the second parameter is a boolean that dictates whether the search is inclusive or exclusive:
- By default, if the second parameter is not provided or set to
true, the search is inclusive, meaning it will return the node with the search key if it exists.
- If the second parameter is
false, the search is exclusive, meaning it will find the next closest node and exclude the node with the exact search key. This is useful for scenarios where you need to find the bounds around a given key.