JS 二叉搜索树 - 笔记
Code:
class TreeNode {
val;
left;
right;
constructor(val, left, right) {
this.val = val ?? 0;
this.left = left ? left : null;
this.right = right ? right : null;
}
}
/**
* 二叉搜索树
*/
class BinarySearchTree {
/**
* @type {TreeNode}
*/
#root;
/**
* @constructor
*/
constructor() {
this.#root = null;
}
getRoot() {
return this.#root;
}
/**
* 插入新节点
* @param {number} num
*/
insert(num) {
if (this.#root === null) {
this.#root = new TreeNode(num);
return;
}
let prev = null;
let cur = this.#root;
// 到达叶子节点后退出
while (cur !== null) {
// 已经存在某个节点的值与待插入的新值相等
if (cur.val === num) {
return;
}
prev = cur;
// 插入值比当前节点的值要大
if (num > cur.val) {
cur = cur.right;
}
// 比当前值小
else {
cur = cur.left;
}
}
const node = new TreeNode(num);
if (num > prev.val) {
prev.right = node;
}
else {
prev.left = node;
}
}
/**
* 查找节点
* @param {number} num
* @returns {TreeNode}
*/
search(num) {
let cur = this.#root;
while (cur !== null) {
if (cur.val < num) {
cur = cur.right;
}
else if (cur.val > num) {
cur = cur.left;
}
else {
break;
}
}
return cur;
}
/**
* 删除节点
* @param {number} num
* @returns
*/
remove(num) {
if (this.#root === null) {
return;
}
let prev = null;
let cur = this.#root;
while (cur !== null) {
if (cur.val === null) {
break;
}
prev = cur;
if (cur.val < num) {
cur = cur.right;
}
else {
cur = cur.left;
}
}
if (cur === null) {
return;
}
//// 子节点数量为 0 或者 1
if (cur.left === null || cur.right === null) {
const child = cur.left === null ? cur.right ? cur.left;
if (cur === this.#root) {
this.#root = child;
}
else {
if (prev.left === cur) {
prev.left = child;
}
else {
prev.right = child;
}
}
}
//// 子节点数量为 2
else {
let tmp = cur.right;
while (tmp.left !== null) {
tmp = tmp.left;
}
this.remove(tmp.val);
cur.val = tmp.val;
}
}
}