On this page
@std/data-structures
Overview Jump to heading
Data structures for use in algorithms and other data manipulation.
import { BinarySearchTree } from "@std/data-structures";
import { assertEquals } from "@std/assert";
const values = [3, 10, 13, 4, 6, 7, 1, 14];
const tree = new BinarySearchTree<number>();
values.forEach((value) => tree.insert(value));
assertEquals([...tree], [1, 3, 4, 6, 7, 10, 13, 14]);
assertEquals(tree.min(), 1);
assertEquals(tree.max(), 14);
assertEquals(tree.find(42), null);
assertEquals(tree.find(7), 7);
assertEquals(tree.remove(42), false);
assertEquals(tree.remove(7), true);
assertEquals([...tree], [1, 3, 4, 6, 10, 13, 14]);
Add to your project Jump to heading
deno add jsr:@std/data-structures
See all symbols in @std/data-structures on
这里“数据结构”的含义 Jump to heading
在此包中,“数据结构”是经过专门设计的容器,具备明确的不变量和可预测的性能特征,超越了 JavaScript 内置的数据结构(Array、Map、Set)。它们提供如以下功能:
-
优先级排序(堆)
-
有序搜索和遍历(树)
-
可反转查找(双向映射)
-
固定形状存储(二维数组)
-
大多数结构实现了
Iterable,因此你可以使用扩展运算符或for..of遍历它们。 -
许多结构接受比较器(例如,
ascend/descend)以控制顺序。
何时使用哪些结构 Jump to heading
- BinaryHeap(二叉堆,优先队列):调度任务,从中选取最高优先级的 k 个元素,Dijkstra/最佳优先搜索。默认是最大堆;可提供自定义比较器来改变优先级。
- RedBlackTree(红黑树,自平衡二叉搜索树):维护一个有序值集合,即使在恶劣输入下也能快速获取最小/最大值并进行中序遍历。
- BinarySearchTree(二叉搜索树,非平衡):简单的树结构,适合大多为随机输入或教学用途;支持遍历顺序和最小/最大值操作。
- BidirectionalMap(双向映射,不稳定版):当键和值均唯一时,实现双向查找(例如,ID ↔ 代码)。
- D2Array(二维数组,不稳定版):固定大小的二维网格(棋盘、矩阵),支持 O(1) 访问。
示例 Jump to heading
import { BinaryHeap } from "@std/data-structures";
// 优先队列(默认最大堆)
const pq = BinaryHeap.from([5, 1, 3]);
pq.pop(); // 5
// 自定义优先级:字符串长度最短优先
const shortestFirst = new BinaryHeap<string>((a, b) => b.length - a.length);
shortestFirst.push("bbb", "a", "cc");
shortestFirst.pop(); // "a"
import { ascend, RedBlackTree } from "@std/data-structures";
const t = RedBlackTree.from([5, 1, 9], ascend<number>);
[...t]; // [1, 5, 9]
t.min(); // 1
t.max(); // 9
// 不稳定子模块
import { BidirectionalMap } from "@std/data-structures/unstable-bidirectional-map";
import { D2Array } from "@std/data-structures/unstable-2d-array";
const bimap = new BidirectionalMap<string, number>();
bimap.set("alice", 1);
bimap.getReverse(1); // "alice"
const grid = new D2Array<number>(3, 2, 0); // 宽度=3,高度=2,初始值=0
grid.resize(4, 2);
grid.insert(1, 1, 42);
grid.get(1, 1); // 42