实现说明
二叉搜索树插入删除可以归结为类 BST和函数 node。
迭代是嵌套的:while (true) 框定这一趟,while (cur) { if (val === cur.val) return true; cur = val < cur.val ? cur.left : cur.right; } 做逐项处理。
返回值是携带 val、null 的对象。
使用要点
- 守卫
val === cur.val一旦成立就走提前的return,把后续流程挡掉。
常见问题
node 会修改传入的参数吗?
不会。代码构造并返回新值,入参保持原样,对共享或冻结的数据结构调用是安全的。
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 node。
签名一览:function node(val: number)
核心语句
while (cur) { if (val === cur.val) return true; cur = val < cur.val ? cur.left : cur.right; }
function node(val: number): TreeNode { return { val, left: null, right: null }; }
代码示例
interface TreeNode { val: number; left: TreeNode | null; right: TreeNode | null; }
function node(val: number): TreeNode { return { val, left: null, right: null }; }
class BST {
root: TreeNode | null = null;
insert(val: number): void {
if (!this.root) { this.root = node(val); return; }
let cur = this.root;
while (true) {
if (val < cur.val) { if (!cur.left) { cur.left = node(val); return; } cur = cur.left; }
else { if (!cur.right) { cur.right = node(val); return; } cur = cur.right; }
}
}
has(val: number): boolean {
let cur = this.root;
while (cur) { if (val === cur.val) return true; cur = val < cur.val ? cur.left : cur.right; }
return false;
}
}