Update JavaScript and TypeScript codes for all chapters, rename JavaScript and TypeScript import folder to modules (#402)

* Update JavaScript and TypeScript codes

* Rename JavaScript and TypeScript import folder to modules
This commit is contained in:
Justin Tse 2023-03-03 01:34:53 +08:00 committed by GitHub
parent 7b41e6c2f0
commit e4a98bc9c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
61 changed files with 324 additions and 290 deletions

View File

@ -4,8 +4,8 @@
* Author: IsChristina (christinaxia77@foxmail.com), Justin (xiefahit@gmail.com) * Author: IsChristina (christinaxia77@foxmail.com), Justin (xiefahit@gmail.com)
*/ */
const { printLinkedList } = require("../include/PrintUtil"); const { printLinkedList } = require("../modules/PrintUtil");
const { ListNode } = require("../include/ListNode"); const { ListNode } = require("../modules/ListNode");
/* 在链表的结点 n0 之后插入结点 P */ /* 在链表的结点 n0 之后插入结点 P */
function insert(n0, P) { function insert(n0, P) {

View File

@ -4,9 +4,9 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
const { ListNode } = require('../include/ListNode'); const { ListNode } = require('../modules/ListNode');
const { TreeNode } = require('../include/TreeNode'); const { TreeNode } = require('../modules/TreeNode');
const { printTree } = require('../include/PrintUtil'); const { printTree } = require('../modules/PrintUtil');
/* 函数 */ /* 函数 */
function constFunc() { function constFunc() {

View File

@ -4,7 +4,7 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
const { Vertex } = require('../include/Vertex') const { Vertex } = require('../modules/Vertex')
/* 基于邻接表实现的无向图类 */ /* 基于邻接表实现的无向图类 */
class GraphAdjList { class GraphAdjList {

View File

@ -92,7 +92,7 @@ class GraphAdjMat {
} }
} }
/* Driver Code */
/* 初始化无向图 */ /* 初始化无向图 */
// 请注意edges 元素代表顶点索引,即对应 vertices 元素索引 // 请注意edges 元素代表顶点索引,即对应 vertices 元素索引
const vertices = [1, 3, 2, 5, 4]; const vertices = [1, 3, 2, 5, 4];

View File

@ -4,10 +4,8 @@
* Author: Zhuo Qinyue (1403450829@qq.com) * Author: Zhuo Qinyue (1403450829@qq.com)
*/ */
const { GraphAdjList } = require('./graph_adjacency_list'); const { GraphAdjList } = require('./graph_adjacency_list');
const { Vertex } = require('../include/Vertex'); const { Vertex } = require('../modules/Vertex');
/* 广度优先遍历 BFS */ /* 广度优先遍历 BFS */
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 // 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
@ -36,7 +34,6 @@ function graphBFS(graph, startVet) {
return res; return res;
} }
/* Driver Code */ /* Driver Code */
/* 初始化无向图 */ /* 初始化无向图 */
const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

View File

@ -4,8 +4,7 @@
* Author: Zhuo Qinyue (1403450829@qq.com) * Author: Zhuo Qinyue (1403450829@qq.com)
*/ */
const { Vertex } = require('../modules/Vertex');
const { Vertex } = require('../include/Vertex');
const { GraphAdjList } = require('./graph_adjacency_list'); const { GraphAdjList } = require('./graph_adjacency_list');
/* 深度优先遍历 DFS */ /* 深度优先遍历 DFS */
@ -34,7 +33,6 @@ function graphDFS(graph, startVet) {
return res; return res;
} }
/* Driver Code */ /* Driver Code */
/* 初始化无向图 */ /* 初始化无向图 */
const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6]); const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6]);

View File

@ -4,7 +4,7 @@
* Author: what-is-me (whatisme@outlook.jp) * Author: what-is-me (whatisme@outlook.jp)
*/ */
const { printHeap } = require("../include/PrintUtil"); const { printHeap } = require("../modules/PrintUtil");
/* 最大堆类 */ /* 最大堆类 */
class MaxHeap { class MaxHeap {

View File

@ -10,7 +10,7 @@ function binarySearch(nums, target) {
let i = 0, j = nums.length - 1; let i = 0, j = nums.length - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空) // 循环,当搜索区间为空时跳出(当 i > j 时为空)
while (i <= j) { while (i <= j) {
let m = parseInt((i + j) / 2); // 计算中点索引 m ,在 JS 中需使用 parseInt 函数取整 const m = parseInt((i + j) / 2); // 计算中点索引 m ,在 JS 中需使用 parseInt 函数取整
if (nums[m] < target) // 此情况说明 target 在区间 [m+1, j] 中 if (nums[m] < target) // 此情况说明 target 在区间 [m+1, j] 中
i = m + 1; i = m + 1;
else if (nums[m] > target) // 此情况说明 target 在区间 [i, m-1] 中 else if (nums[m] > target) // 此情况说明 target 在区间 [i, m-1] 中
@ -28,7 +28,7 @@ function binarySearch1(nums, target) {
let i = 0, j = nums.length; let i = 0, j = nums.length;
// 循环,当搜索区间为空时跳出(当 i = j 时为空) // 循环,当搜索区间为空时跳出(当 i = j 时为空)
while (i < j) { while (i < j) {
let m = parseInt((i + j) / 2); // 计算中点索引 m ,在 JS 中需使用 parseInt 函数取整 const m = parseInt((i + j) / 2); // 计算中点索引 m ,在 JS 中需使用 parseInt 函数取整
if (nums[m] < target) // 此情况说明 target 在区间 [m+1, j) 中 if (nums[m] < target) // 此情况说明 target 在区间 [m+1, j) 中
i = m + 1; i = m + 1;
else if (nums[m] > target) // 此情况说明 target 在区间 [i, m) 中 else if (nums[m] > target) // 此情况说明 target 在区间 [i, m) 中
@ -41,11 +41,11 @@ function binarySearch1(nums, target) {
} }
/* Driver Code */ /* Driver Code */
var target = 6; const target = 6;
var nums = [1, 3, 6, 8, 12, 15, 23, 67, 70, 92]; const nums = [1, 3, 6, 8, 12, 15, 23, 67, 70, 92];
/* 二分查找(双闭区间) */ /* 二分查找(双闭区间) */
var index = binarySearch(nums, target); let index = binarySearch(nums, target);
console.log("目标元素 6 的索引 = " + index); console.log("目标元素 6 的索引 = " + index);
/* 二分查找(左闭右开) */ /* 二分查找(左闭右开) */

View File

@ -4,7 +4,7 @@
* Author: Zhuo Qinyue (1403450829@qq.com) * Author: Zhuo Qinyue (1403450829@qq.com)
*/ */
const { ListNode, arrToLinkedList } = require("../include/ListNode"); const { arrToLinkedList } = require("../modules/ListNode");
/* 哈希查找(数组) */ /* 哈希查找(数组) */
function hashingSearchArray(map, target) { function hashingSearchArray(map, target) {

View File

@ -4,7 +4,7 @@
* Author: JoseHung (szhong@link.cuhk.edu.hk) * Author: JoseHung (szhong@link.cuhk.edu.hk)
*/ */
const { ListNode, arrToLinkedList } = require("../include/ListNode"); const { ListNode, arrToLinkedList } = require("../modules/ListNode");
/* 线性查找(数组) */ /* 线性查找(数组) */
function linearSearchArray(nums, target) { function linearSearchArray(nums, target) {

View File

@ -1,5 +1,5 @@
/** /**
* File: quick_sort.js * File: bubble_sort.js
* Created Time: 2022-12-01 * Created Time: 2022-12-01
* Author: IsChristina (christinaxia77@foxmail.com) * Author: IsChristina (christinaxia77@foxmail.com)
*/ */

View File

@ -1,5 +1,5 @@
/** /**
* File: quick_sort.js * File: insertion_sort.js
* Created Time: 2022-12-01 * Created Time: 2022-12-01
* Author: IsChristina (christinaxia77@foxmail.com) * Author: IsChristina (christinaxia77@foxmail.com)
*/ */

View File

@ -1,5 +1,5 @@
/** /**
* File: quick_sort.js * File: merge_sort.js
* Created Time: 2022-12-01 * Created Time: 2022-12-01
* Author: IsChristina (christinaxia77@foxmail.com) * Author: IsChristina (christinaxia77@foxmail.com)
*/ */
@ -44,6 +44,6 @@ function mergeSort(nums, left, right) {
} }
/* Driver Code */ /* Driver Code */
const nums = [ 7, 3, 2, 6, 0, 1, 5, 4 ] const nums = [7, 3, 2, 6, 0, 1, 5, 4];
mergeSort(nums, 0, nums.length - 1) mergeSort(nums, 0, nums.length - 1);
console.log('归并排序完成后 nums =', nums) console.log('归并排序完成后 nums =', nums);

View File

@ -7,49 +7,48 @@
/* 基于数组实现的栈 */ /* 基于数组实现的栈 */
class ArrayStack { class ArrayStack {
stack; #stack;
constructor() { constructor() {
this.stack = []; this.#stack = [];
} }
/* 获取栈的长度 */ /* 获取栈的长度 */
get size() { get size() {
return this.stack.length; return this.#stack.length;
} }
/* 判断栈是否为空 */ /* 判断栈是否为空 */
empty() { empty() {
return this.stack.length === 0; return this.#stack.length === 0;
} }
/* 入栈 */ /* 入栈 */
push(num) { push(num) {
this.stack.push(num); this.#stack.push(num);
} }
/* 出栈 */ /* 出栈 */
pop() { pop() {
if (this.empty()) if (this.empty())
throw new Error("栈为空"); throw new Error("栈为空");
return this.stack.pop(); return this.#stack.pop();
} }
/* 访问栈顶元素 */ /* 访问栈顶元素 */
top() { top() {
if (this.empty()) if (this.empty())
throw new Error("栈为空"); throw new Error("栈为空");
return this.stack[this.stack.length - 1]; return this.#stack[this.#stack.length - 1];
} }
/* 返回 Array */ /* 返回 Array */
toArray() { toArray() {
return this.stack; return this.#stack;
} }
}; };
/* Driver Code */ /* Driver Code */
/* 初始化栈 */ /* 初始化栈 */
const stack = new ArrayStack(); const stack = new ArrayStack();

View File

@ -4,6 +4,7 @@
* Author: Zhuo Qinyue (1403450829@qq.com) * Author: Zhuo Qinyue (1403450829@qq.com)
*/ */
/* Driver Code */
/* 初始化双向队列 */ /* 初始化双向队列 */
// JavaScript 没有内置的双端队列,只能把 Array 当作双端队列来使用 // JavaScript 没有内置的双端队列,只能把 Array 当作双端队列来使用
const deque = []; const deque = [];

View File

@ -19,106 +19,106 @@ class ListNode {
/* 基于双向链表实现的双向队列 */ /* 基于双向链表实现的双向队列 */
class LinkedListDeque { class LinkedListDeque {
front; // 头结点 front #front; // 头结点 front
rear; // 尾结点 rear #rear; // 尾结点 rear
len; // 双向队列的长度 #queSize; // 双向队列的长度
constructor() { constructor() {
this.front = null; this.#front = null;
this.rear = null; this.#rear = null;
this.len = 0; this.#queSize = 0;
} }
/* 队尾入队操作 */ /* 队尾入队操作 */
pushLast(val) { pushLast(val) {
const node = new ListNode(val); const node = new ListNode(val);
// 若链表为空,则令 front, rear 都指向 node // 若链表为空,则令 front, rear 都指向 node
if (this.len === 0) { if (this.#queSize === 0) {
this.front = node; this.#front = node;
this.rear = node; this.#rear = node;
} else { } else {
// 将 node 添加至链表尾部 // 将 node 添加至链表尾部
this.rear.next = node; this.#rear.next = node;
node.prev = this.rear; node.prev = this.#rear;
this.rear = node; // 更新尾结点 this.#rear = node; // 更新尾结点
} }
this.len++; this.#queSize++;
} }
/* 队首入队操作 */ /* 队首入队操作 */
pushFirst(val) { pushFirst(val) {
const node = new ListNode(val); const node = new ListNode(val);
// 若链表为空,则令 front, rear 都指向 node // 若链表为空,则令 front, rear 都指向 node
if (this.len === 0) { if (this.#queSize === 0) {
this.front = node; this.#front = node;
this.rear = node; this.#rear = node;
} else { } else {
// 将 node 添加至链表头部 // 将 node 添加至链表头部
this.front.prev = node; this.#front.prev = node;
node.next = this.front; node.next = this.#front;
this.front = node; // 更新头结点 this.#front = node; // 更新头结点
} }
this.len++; this.#queSize++;
} }
/* 队尾出队操作 */ /* 队尾出队操作 */
pollLast() { pollLast() {
if (this.len === 0) { if (this.#queSize === 0) {
return null; return null;
} }
const value = this.rear.val; // 存储尾结点值 const value = this.#rear.val; // 存储尾结点值
// 删除尾结点 // 删除尾结点
let temp = this.rear.prev; let temp = this.#rear.prev;
if (temp !== null) { if (temp !== null) {
temp.next = null; temp.next = null;
this.rear.prev = null; this.#rear.prev = null;
} }
this.rear = temp; // 更新尾结点 this.#rear = temp; // 更新尾结点
this.len--; this.#queSize--;
return value; return value;
} }
/* 队首出队操作 */ /* 队首出队操作 */
pollFirst() { pollFirst() {
if (this.len === 0) { if (this.#queSize === 0) {
return null; return null;
} }
const value = this.front.val; // 存储尾结点值 const value = this.#front.val; // 存储尾结点值
// 删除头结点 // 删除头结点
let temp = this.front.next; let temp = this.#front.next;
if (temp !== null) { if (temp !== null) {
temp.prev = null; temp.prev = null;
this.front.next = null; this.#front.next = null;
} }
this.front = temp; // 更新头结点 this.#front = temp; // 更新头结点
this.len--; this.#queSize--;
return value; return value;
} }
/* 访问队尾元素 */ /* 访问队尾元素 */
peekLast() { peekLast() {
return this.len === 0 ? null : this.rear.val; return this.#queSize === 0 ? null : this.#rear.val;
} }
/* 访问队首元素 */ /* 访问队首元素 */
peekFirst() { peekFirst() {
return this.len === 0 ? null : this.front.val; return this.#queSize === 0 ? null : this.#front.val;
} }
/* 获取双向队列的长度 */ /* 获取双向队列的长度 */
size() { size() {
return this.len; return this.#queSize;
} }
/* 判断双向队列是否为空 */ /* 判断双向队列是否为空 */
isEmpty() { isEmpty() {
return this.len === 0; return this.#queSize === 0;
} }
/* 打印双向队列 */ /* 打印双向队列 */
print() { print() {
const arr = []; const arr = [];
let temp = this.front; let temp = this.#front;
while (temp !== null) { while (temp !== null) {
arr.push(temp.val); arr.push(temp.val);
temp = temp.next; temp = temp.next;
@ -127,6 +127,7 @@ class LinkedListDeque {
} }
} }
/* Driver Code */
/* 初始化双向队列 */ /* 初始化双向队列 */
const linkedListDeque = new LinkedListDeque(); const linkedListDeque = new LinkedListDeque();
linkedListDeque.pushLast(3); linkedListDeque.pushLast(3);

View File

@ -4,7 +4,7 @@
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com) * Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/ */
const { ListNode } = require("../include/ListNode"); const { ListNode } = require("../modules/ListNode");
/* 基于链表实现的队列 */ /* 基于链表实现的队列 */
class LinkedListQueue { class LinkedListQueue {

View File

@ -4,7 +4,7 @@
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com) * Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/ */
const { ListNode } = require("../include/ListNode"); const { ListNode } = require("../modules/ListNode");
/* 基于链表实现的栈 */ /* 基于链表实现的栈 */
class LinkedListStack { class LinkedListStack {
@ -60,7 +60,7 @@ class LinkedListStack {
} }
} }
/* Driver Code */
/* 初始化栈 */ /* 初始化栈 */
const stack = new LinkedListStack(); const stack = new LinkedListStack();

View File

@ -4,7 +4,6 @@
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com) * Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/ */
/* Driver Code */ /* Driver Code */
/* 初始化队列 */ /* 初始化队列 */
// JavaScript 没有内置的队列,可以把 Array 当作队列来使用 // JavaScript 没有内置的队列,可以把 Array 当作队列来使用
@ -16,16 +15,21 @@ queue.push(3);
queue.push(2); queue.push(2);
queue.push(5); queue.push(5);
queue.push(4); queue.push(4);
console.log("队列 queue =", queue);
/* 访问队首元素 */ /* 访问队首元素 */
const peek = queue[0]; const peek = queue[0];
console.log("队首元素 peek =", peek);
/* 元素出队 */ /* 元素出队 */
// 底层是数组,因此 shift() 方法的时间复杂度为 O(n) // 底层是数组,因此 shift() 方法的时间复杂度为 O(n)
const poll = queue.shift(); const poll = queue.shift();
console.log("出队元素 poll =", poll, ",出队后 queue = ", queue);
/* 获取队列的长度 */ /* 获取队列的长度 */
const size = queue.length; const size = queue.length;
console.log("队列长度 size =", size);
/* 判断队列是否为空 */ /* 判断队列是否为空 */
const empty = queue.length === 0; const isEmpty = queue.length === 0;
console.log("队列是否为空 = ", isEmpty);

View File

@ -4,7 +4,6 @@
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com) * Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/ */
/* Driver Code */ /* Driver Code */
/* 初始化栈 */ /* 初始化栈 */
// Javascript 没有内置的栈类,可以把 Array 当作栈来使用 // Javascript 没有内置的栈类,可以把 Array 当作栈来使用
@ -16,21 +15,21 @@ stack.push(3);
stack.push(2); stack.push(2);
stack.push(5); stack.push(5);
stack.push(4); stack.push(4);
console.log("栈 stack =", stack) console.log("栈 stack =", stack);
/* 访问栈顶元素 */ /* 访问栈顶元素 */
const peek = stack[stack.length - 1]; const peek = stack[stack.length - 1];
console.log("栈顶元素 peek =", peek) console.log("栈顶元素 peek =", peek);
/* 元素出栈 */ /* 元素出栈 */
const pop = stack.pop(); const pop = stack.pop();
console.log("出栈元素 pop =", pop) console.log("出栈元素 pop =", pop);
console.log("出栈后 stack =", stack) console.log("出栈后 stack =", stack);
/* 获取栈的长度 */ /* 获取栈的长度 */
const size = stack.length; const size = stack.length;
console.log("栈的长度 size =", size) console.log("栈的长度 size =", size);
/* 判断是否为空 */ /* 判断是否为空 */
const is_empty = stack.length === 0; const isEmpty = stack.length === 0;
console.log("栈是否为空 =", is_empty) console.log("栈是否为空 =", isEmpty);

View File

@ -4,8 +4,8 @@
* Author: what-is-me (whatisme@outlook.jp) * Author: what-is-me (whatisme@outlook.jp)
*/ */
const { TreeNode } = require("../include/TreeNode"); const { TreeNode } = require("../modules/TreeNode");
const { printTree } = require("../include/PrintUtil"); const { printTree } = require("../modules/PrintUtil");
/* AVL 树*/ /* AVL 树*/
class AVLTree { class AVLTree {
@ -21,7 +21,7 @@ class AVLTree {
} }
/* 更新结点高度 */ /* 更新结点高度 */
updateHeight(node) { #updateHeight(node) {
// 结点高度等于最高子树高度 + 1 // 结点高度等于最高子树高度 + 1
node.height = Math.max(this.height(node.left), this.height(node.right)) + 1; node.height = Math.max(this.height(node.left), this.height(node.right)) + 1;
} }
@ -35,57 +35,57 @@ class AVLTree {
} }
/* 右旋操作 */ /* 右旋操作 */
rightRotate(node) { #rightRotate(node) {
const child = node.left; const child = node.left;
const grandChild = child.right; const grandChild = child.right;
// 以 child 为原点,将 node 向右旋转 // 以 child 为原点,将 node 向右旋转
child.right = node; child.right = node;
node.left = grandChild; node.left = grandChild;
// 更新结点高度 // 更新结点高度
this.updateHeight(node); this.#updateHeight(node);
this.updateHeight(child); this.#updateHeight(child);
// 返回旋转后子树的根结点 // 返回旋转后子树的根结点
return child; return child;
} }
/* 左旋操作 */ /* 左旋操作 */
leftRotate(node) { #leftRotate(node) {
const child = node.right; const child = node.right;
const grandChild = child.left; const grandChild = child.left;
// 以 child 为原点,将 node 向左旋转 // 以 child 为原点,将 node 向左旋转
child.left = node; child.left = node;
node.right = grandChild; node.right = grandChild;
// 更新结点高度 // 更新结点高度
this.updateHeight(node); this.#updateHeight(node);
this.updateHeight(child); this.#updateHeight(child);
// 返回旋转后子树的根结点 // 返回旋转后子树的根结点
return child; return child;
} }
/* 执行旋转操作,使该子树重新恢复平衡 */ /* 执行旋转操作,使该子树重新恢复平衡 */
rotate(node) { #rotate(node) {
// 获取结点 node 的平衡因子 // 获取结点 node 的平衡因子
const balanceFactor = this.balanceFactor(node); const balanceFactor = this.balanceFactor(node);
// 左偏树 // 左偏树
if (balanceFactor > 1) { if (balanceFactor > 1) {
if (this.balanceFactor(node.left) >= 0) { if (this.balanceFactor(node.left) >= 0) {
// 右旋 // 右旋
return this.rightRotate(node); return this.#rightRotate(node);
} else { } else {
// 先左旋后右旋 // 先左旋后右旋
node.left = this.leftRotate(node.left); node.left = this.#leftRotate(node.left);
return this.rightRotate(node); return this.#rightRotate(node);
} }
} }
// 右偏树 // 右偏树
if (balanceFactor < -1) { if (balanceFactor < -1) {
if (this.balanceFactor(node.right) <= 0) { if (this.balanceFactor(node.right) <= 0) {
// 左旋 // 左旋
return this.leftRotate(node); return this.#leftRotate(node);
} else { } else {
// 先右旋后左旋 // 先右旋后左旋
node.right = this.rightRotate(node.right); node.right = this.#rightRotate(node.right);
return this.leftRotate(node); return this.#leftRotate(node);
} }
} }
// 平衡树,无需旋转,直接返回 // 平衡树,无需旋转,直接返回
@ -94,36 +94,36 @@ class AVLTree {
/* 插入结点 */ /* 插入结点 */
insert(val) { insert(val) {
this.root = this.insertHelper(this.root, val); this.root = this.#insertHelper(this.root, val);
return this.root; return this.root;
} }
/* 递归插入结点(辅助方法) */ /* 递归插入结点(辅助方法) */
insertHelper(node, val) { #insertHelper(node, val) {
if (node === null) return new TreeNode(val); if (node === null) return new TreeNode(val);
/* 1. 查找插入位置,并插入结点 */ /* 1. 查找插入位置,并插入结点 */
if (val < node.val) node.left = this.insertHelper(node.left, val); if (val < node.val) node.left = this.#insertHelper(node.left, val);
else if (val > node.val) node.right = this.insertHelper(node.right, val); else if (val > node.val) node.right = this.#insertHelper(node.right, val);
else return node; // 重复结点不插入,直接返回 else return node; // 重复结点不插入,直接返回
this.updateHeight(node); // 更新结点高度 this.#updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = this.rotate(node); node = this.#rotate(node);
// 返回子树的根结点 // 返回子树的根结点
return node; return node;
} }
/* 删除结点 */ /* 删除结点 */
remove(val) { remove(val) {
this.root = this.removeHelper(this.root, val); this.root = this.#removeHelper(this.root, val);
return this.root; return this.root;
} }
/* 递归删除结点(辅助方法) */ /* 递归删除结点(辅助方法) */
removeHelper(node, val) { #removeHelper(node, val) {
if (node === null) return null; if (node === null) return null;
/* 1. 查找结点,并删除之 */ /* 1. 查找结点,并删除之 */
if (val < node.val) node.left = this.removeHelper(node.left, val); if (val < node.val) node.left = this.#removeHelper(node.left, val);
else if (val > node.val) node.right = this.removeHelper(node.right, val); else if (val > node.val) node.right = this.#removeHelper(node.right, val);
else { else {
if (node.left === null || node.right === null) { if (node.left === null || node.right === null) {
const child = node.left !== null ? node.left : node.right; const child = node.left !== null ? node.left : node.right;
@ -133,20 +133,20 @@ class AVLTree {
else node = child; else node = child;
} else { } else {
// 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点 // 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点
const temp = this.getInOrderNext(node.right); const temp = this.#getInOrderNext(node.right);
node.right = this.removeHelper(node.right, temp.val); node.right = this.#removeHelper(node.right, temp.val);
node.val = temp.val; node.val = temp.val;
} }
} }
this.updateHeight(node); // 更新结点高度 this.#updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = this.rotate(node); node = this.#rotate(node);
// 返回子树的根结点 // 返回子树的根结点
return node; return node;
} }
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */ /* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
getInOrderNext(node) { #getInOrderNext(node) {
if (node === null) return node; if (node === null) return node;
// 循环访问左子结点,直到叶结点时为最小结点,跳出 // 循环访问左子结点,直到叶结点时为最小结点,跳出
while (node.left !== null) { while (node.left !== null) {

View File

@ -1,14 +1,14 @@
/** /**
* File: binary_tree.js * File: binary_search_tree.js
* Created Time: 2022-12-04 * Created Time: 2022-12-04
* Author: IsChristina (christinaxia77@foxmail.com) * Author: IsChristina (christinaxia77@foxmail.com)
*/ */
const Tree = require("../include/TreeNode"); const { TreeNode } = require("../modules/TreeNode");
const { printTree } = require("../include/PrintUtil"); const { printTree } = require("../modules/PrintUtil");
/* 二叉搜索树 */ /* 二叉搜索树 */
var root; let root;
function BinarySearchTree(nums) { function BinarySearchTree(nums) {
nums.sort((a, b) => { return a - b }); // 排序数组 nums.sort((a, b) => { return a - b }); // 排序数组
@ -25,7 +25,7 @@ function buildTree(nums, i, j) {
if (i > j) return null; if (i > j) return null;
// 将数组中间结点作为根结点 // 将数组中间结点作为根结点
let mid = Math.floor((i + j) / 2); let mid = Math.floor((i + j) / 2);
let root = new Tree.TreeNode(nums[mid]); let root = new TreeNode(nums[mid]);
// 递归建立左子树和右子树 // 递归建立左子树和右子树
root.left = buildTree(nums, i, mid - 1); root.left = buildTree(nums, i, mid - 1);
root.right = buildTree(nums, mid + 1, j); root.right = buildTree(nums, mid + 1, j);
@ -64,7 +64,7 @@ function insert(num) {
else cur = cur.left; else cur = cur.left;
} }
// 插入结点 val // 插入结点 val
let node = new Tree.TreeNode(num); let node = new TreeNode(num);
if (pre.val < num) pre.right = node; if (pre.val < num) pre.right = node;
else pre.left = node; else pre.left = node;
return node; return node;
@ -120,7 +120,7 @@ function getInOrderNext(root) {
/* Driver Code */ /* Driver Code */
/* 初始化二叉搜索树 */ /* 初始化二叉搜索树 */
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
BinarySearchTree(nums); BinarySearchTree(nums);
console.log("\n初始化的二叉树为\n"); console.log("\n初始化的二叉树为\n");
printTree(getRoot()); printTree(getRoot());

View File

@ -4,16 +4,16 @@
* Author: IsChristina (christinaxia77@foxmail.com) * Author: IsChristina (christinaxia77@foxmail.com)
*/ */
const Tree = require("../include/TreeNode"); const { TreeNode } = require("../modules/TreeNode");
const { printTree } = require("../include/PrintUtil"); const { printTree } = require("../modules/PrintUtil");
/* 初始化二叉树 */ /* 初始化二叉树 */
// 初始化结点 // 初始化结点
let n1 = new Tree.TreeNode(1), let n1 = new TreeNode(1),
n2 = new Tree.TreeNode(2), n2 = new TreeNode(2),
n3 = new Tree.TreeNode(3), n3 = new TreeNode(3),
n4 = new Tree.TreeNode(4), n4 = new TreeNode(4),
n5 = new Tree.TreeNode(5); n5 = new TreeNode(5);
// 构建引用指向(即指针) // 构建引用指向(即指针)
n1.left = n2; n1.left = n2;
n1.right = n3; n1.right = n3;
@ -23,7 +23,7 @@ console.log("\n初始化二叉树\n");
printTree(n1); printTree(n1);
/* 插入与删除结点 */ /* 插入与删除结点 */
let P = new Tree.TreeNode(0); const P = new TreeNode(0);
// 在 n1 -> n2 中间插入结点 P // 在 n1 -> n2 中间插入结点 P
n1.left = P; n1.left = P;
P.left = n2; P.left = n2;

View File

@ -1,18 +1,18 @@
/** /**
* File: binary_tree.js * File: binary_tree_bfs.js
* Created Time: 2022-12-04 * Created Time: 2022-12-04
* Author: IsChristina (christinaxia77@foxmail.com) * Author: IsChristina (christinaxia77@foxmail.com)
*/ */
const { arrToTree } = require("../include/TreeNode"); const { arrToTree } = require("../modules/TreeNode");
const { printTree } = require("../include/PrintUtil"); const { printTree } = require("../modules/PrintUtil");
/* 层序遍历 */ /* 层序遍历 */
function levelOrder(root) { function levelOrder(root) {
// 初始化队列,加入根结点 // 初始化队列,加入根结点
let queue = [root]; const queue = [root];
// 初始化一个列表,用于保存遍历序列 // 初始化一个列表,用于保存遍历序列
let list = []; const list = [];
while (queue.length) { while (queue.length) {
let node = queue.shift(); // 队列出队 let node = queue.shift(); // 队列出队
list.push(node.val); // 保存结点值 list.push(node.val); // 保存结点值
@ -28,10 +28,10 @@ function levelOrder(root) {
/* Driver Code */ /* Driver Code */
/* 初始化二叉树 */ /* 初始化二叉树 */
// 这里借助了一个从数组直接生成二叉树的函数 // 这里借助了一个从数组直接生成二叉树的函数
var root = arrToTree([1, 2, 3, 4, 5, 6, 7]); const root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
console.log("\n初始化二叉树\n"); console.log("\n初始化二叉树\n");
printTree(root); printTree(root);
/* 层序遍历 */ /* 层序遍历 */
let list = levelOrder(root); const list = levelOrder(root);
console.log("\n层序遍历的结点打印序列 = " + list); console.log("\n层序遍历的结点打印序列 = " + list);

View File

@ -1,14 +1,14 @@
/** /**
* File: binary_tree.js * File: binary_tree_dfs.js
* Created Time: 2022-12-04 * Created Time: 2022-12-04
* Author: IsChristina (christinaxia77@foxmail.com) * Author: IsChristina (christinaxia77@foxmail.com)
*/ */
const { arrToTree } = require("../include/TreeNode"); const { arrToTree } = require("../modules/TreeNode");
const { printTree } = require("../include/PrintUtil"); const { printTree } = require("../modules/PrintUtil");
// 初始化列表,用于存储遍历序列 // 初始化列表,用于存储遍历序列
var list = []; const list = [];
/* 前序遍历 */ /* 前序遍历 */
function preOrder(root) { function preOrder(root) {
@ -40,7 +40,7 @@ function postOrder(root) {
/* Driver Code */ /* Driver Code */
/* 初始化二叉树 */ /* 初始化二叉树 */
// 这里借助了一个从数组直接生成二叉树的函数 // 这里借助了一个从数组直接生成二叉树的函数
var root = arrToTree([1, 2, 3, 4, 5, 6, 7]); const root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
console.log("\n初始化二叉树\n"); console.log("\n初始化二叉树\n");
printTree(root); printTree(root);

View File

@ -98,5 +98,5 @@ function printHeap(arr) {
module.exports = { module.exports = {
printLinkedList, printLinkedList,
printTree, printTree,
printHeap, printHeap
}; };

View File

@ -50,5 +50,5 @@ function arrToTree(arr) {
module.exports = { module.exports = {
TreeNode, TreeNode,
arrToTree, arrToTree
}; };

View File

@ -1,5 +1,5 @@
/** /**
* File: Vertex.ts * File: Vertex.js
* Created Time: 2023-02-15 * Created Time: 2023-02-15
* Author: Zhuo Qinyue (1403450829@qq.com) * Author: Zhuo Qinyue (1403450829@qq.com)
*/ */

View File

@ -70,13 +70,13 @@ function find(nums: number[], target: number): number {
/* Driver Code */ /* Driver Code */
/* 初始化数组 */ /* 初始化数组 */
let arr: number[] = new Array(5).fill(0); const arr: number[] = new Array(5).fill(0);
console.log('数组 arr =', arr); console.log('数组 arr =', arr);
let nums: number[] = [1, 3, 2, 5, 4]; let nums: number[] = [1, 3, 2, 5, 4];
console.log('数组 nums =', nums); console.log('数组 nums =', nums);
/* 随机访问 */ /* 随机访问 */
const random_num = randomAccess(nums); let random_num = randomAccess(nums);
console.log('在 nums 中获取随机元素', random_num); console.log('在 nums 中获取随机元素', random_num);
/* 长度扩展 */ /* 长度扩展 */
@ -95,7 +95,7 @@ console.log('删除索引 2 处的元素,得到 nums =', nums);
traverse(nums); traverse(nums);
/* 查找元素 */ /* 查找元素 */
var index: number = find(nums, 3); let index = find(nums, 3);
console.log('在 nums 中查找元素 3 ,得到索引 =', index); console.log('在 nums 中查找元素 3 ,得到索引 =', index);
export {}; export {};

View File

@ -4,8 +4,8 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
import { ListNode } from '../module/ListNode'; import { ListNode } from '../modules/ListNode';
import { printLinkedList } from '../module/PrintUtil'; import { printLinkedList } from '../modules/PrintUtil';
/* 在链表的结点 n0 之后插入结点 P */ /* 在链表的结点 n0 之后插入结点 P */
function insert(n0: ListNode, P: ListNode): void { function insert(n0: ListNode, P: ListNode): void {

View File

@ -97,7 +97,7 @@ class MyList {
public toArray(): number[] { public toArray(): number[] {
let size = this.size(); let size = this.size();
// 仅转换有效长度范围内的列表元素 // 仅转换有效长度范围内的列表元素
let nums = new Array(size); const nums = new Array(size);
for (let i = 0; i < size; i++) { for (let i = 0; i < size; i++) {
nums[i] = this.get(i); nums[i] = this.get(i);
} }
@ -107,7 +107,7 @@ class MyList {
/* Driver Code */ /* Driver Code */
/* 初始化列表 */ /* 初始化列表 */
let list = new MyList(); const list = new MyList();
/* 尾部添加元素 */ /* 尾部添加元素 */
list.add(1); list.add(1);
list.add(3); list.add(3);
@ -127,7 +127,7 @@ list.remove(3);
console.log(`删除索引 3 处的元素,得到 list = ${list.toArray()}`); console.log(`删除索引 3 处的元素,得到 list = ${list.toArray()}`);
/* 访问元素 */ /* 访问元素 */
let num = list.get(1); const num = list.get(1);
console.log(`访问索引 1 处的元素,得到 num = ${num}`); console.log(`访问索引 1 处的元素,得到 num = ${num}`);
/* 更新元素 */ /* 更新元素 */

View File

@ -4,9 +4,9 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
import { ListNode } from '../module/ListNode'; import { ListNode } from '../modules/ListNode';
import { TreeNode } from '../module/TreeNode'; import { TreeNode } from '../modules/TreeNode';
import { printTree } from '../module/PrintUtil'; import { printTree } from '../modules/PrintUtil';
/* 函数 */ /* 函数 */
function constFunc(): number { function constFunc(): number {
@ -57,7 +57,9 @@ function linearRecur(n: number): void {
/* 平方阶 */ /* 平方阶 */
function quadratic(n: number): void { function quadratic(n: number): void {
// 矩阵占用 O(n^2) 空间 // 矩阵占用 O(n^2) 空间
const numMatrix = Array(n).fill(null).map(() => Array(n).fill(null)); const numMatrix = Array(n)
.fill(null)
.map(() => Array(n).fill(null));
// 二维列表占用 O(n^2) 空间 // 二维列表占用 O(n^2) 空间
const numList = []; const numList = [];
for (let i = 0; i < n; i++) { for (let i = 0; i < n; i++) {

View File

@ -4,7 +4,7 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
import { Vertex } from "../module/Vertex"; import { Vertex } from '../modules/Vertex';
/* 基于邻接表实现的无向图类 */ /* 基于邻接表实现的无向图类 */
class GraphAdjList { class GraphAdjList {
@ -30,7 +30,7 @@ class GraphAdjList {
/* 添加边 */ /* 添加边 */
addEdge(vet1: Vertex, vet2: Vertex): void { addEdge(vet1: Vertex, vet2: Vertex): void {
if (!this.adjList.has(vet1) || !this.adjList.has(vet2) || vet1 === vet2) { if (!this.adjList.has(vet1) || !this.adjList.has(vet2) || vet1 === vet2) {
throw new Error("Illegal Argument Exception"); throw new Error('Illegal Argument Exception');
} }
// 添加边 vet1 - vet2 // 添加边 vet1 - vet2
this.adjList.get(vet1).push(vet2); this.adjList.get(vet1).push(vet2);
@ -40,7 +40,7 @@ class GraphAdjList {
/* 删除边 */ /* 删除边 */
removeEdge(vet1: Vertex, vet2: Vertex): void { removeEdge(vet1: Vertex, vet2: Vertex): void {
if (!this.adjList.has(vet1) || !this.adjList.has(vet2) || vet1 === vet2) { if (!this.adjList.has(vet1) || !this.adjList.has(vet2) || vet1 === vet2) {
throw new Error("Illegal Argument Exception"); throw new Error('Illegal Argument Exception');
} }
// 删除边 vet1 - vet2 // 删除边 vet1 - vet2
this.adjList.get(vet1).splice(this.adjList.get(vet1).indexOf(vet2), 1); this.adjList.get(vet1).splice(this.adjList.get(vet1).indexOf(vet2), 1);
@ -57,7 +57,7 @@ class GraphAdjList {
/* 删除顶点 */ /* 删除顶点 */
removeVertex(vet: Vertex): void { removeVertex(vet: Vertex): void {
if (!this.adjList.has(vet)) { if (!this.adjList.has(vet)) {
throw new Error("Illegal Argument Exception"); throw new Error('Illegal Argument Exception');
} }
// 在邻接表中删除顶点 vet 对应的链表 // 在邻接表中删除顶点 vet 对应的链表
this.adjList.delete(vet); this.adjList.delete(vet);
@ -72,13 +72,13 @@ class GraphAdjList {
/* 打印邻接表 */ /* 打印邻接表 */
print(): void { print(): void {
console.log("邻接表 ="); console.log('邻接表 =');
for (const [key, value] of this.adjList.entries()) { for (const [key, value] of this.adjList.entries()) {
const tmp = []; const tmp = [];
for (const vertex of value) { for (const vertex of value) {
tmp.push(vertex.val); tmp.push(vertex.val);
} }
console.log(key.val + ": " + tmp.join()); console.log(key.val + ': ' + tmp.join());
} }
} }
} }
@ -92,33 +92,40 @@ if (require.main === module) {
v2 = new Vertex(2), v2 = new Vertex(2),
v3 = new Vertex(5), v3 = new Vertex(5),
v4 = new Vertex(4); v4 = new Vertex(4);
const edges = [[v0, v1], [v1, v2], [v2, v3], [v0, v3], [v2, v4], [v3, v4]]; const edges = [
[v0, v1],
[v1, v2],
[v2, v3],
[v0, v3],
[v2, v4],
[v3, v4]
];
const graph = new GraphAdjList(edges); const graph = new GraphAdjList(edges);
console.log("\n初始化后图为"); console.log('\n初始化后图为');
graph.print(); graph.print();
/* 添加边 */ /* 添加边 */
// 顶点 1, 2 即 v0, v2 // 顶点 1, 2 即 v0, v2
graph.addEdge(v0, v2); graph.addEdge(v0, v2);
console.log("\n添加边 1-2 后,图为"); console.log('\n添加边 1-2 后,图为');
graph.print(); graph.print();
/* 删除边 */ /* 删除边 */
// 顶点 1, 3 即 v0, v1 // 顶点 1, 3 即 v0, v1
graph.removeEdge(v0, v1); graph.removeEdge(v0, v1);
console.log("\n删除边 1-3 后,图为"); console.log('\n删除边 1-3 后,图为');
graph.print(); graph.print();
/* 添加顶点 */ /* 添加顶点 */
const v5 = new Vertex(6); const v5 = new Vertex(6);
graph.addVertex(v5); graph.addVertex(v5);
console.log("\n添加顶点 6 后,图为"); console.log('\n添加顶点 6 后,图为');
graph.print(); graph.print();
/* 删除顶点 */ /* 删除顶点 */
// 顶点 3 即 v1 // 顶点 3 即 v1
graph.removeVertex(v1); graph.removeVertex(v1);
console.log("\n删除顶点 3 后,图为"); console.log('\n删除顶点 3 后,图为');
graph.print(); graph.print();
} }

View File

@ -92,7 +92,7 @@ class GraphAdjMat {
} }
} }
/* Driver Code */
/* 初始化无向图 */ /* 初始化无向图 */
// 请注意edges 元素代表顶点索引,即对应 vertices 元素索引 // 请注意edges 元素代表顶点索引,即对应 vertices 元素索引
const vertices: number[] = [1, 3, 2, 5, 4]; const vertices: number[] = [1, 3, 2, 5, 4];

View File

@ -4,9 +4,8 @@
* Author: Zhuo Qinyue (1403450829@qq.com) * Author: Zhuo Qinyue (1403450829@qq.com)
*/ */
import { GraphAdjList } from './graph_adjacency_list';
import { GraphAdjList } from './graph_adjacency_list' import { Vertex } from '../modules/Vertex';
import { Vertex } from '../module/Vertex';
/* 广度优先遍历 BFS */ /* 广度优先遍历 BFS */
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 // 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
@ -20,33 +19,43 @@ function graphBFS(graph: GraphAdjList, startVet: Vertex): Vertex[] {
const que = [startVet]; const que = [startVet];
// 以顶点 vet 为起点,循环直至访问完所有顶点 // 以顶点 vet 为起点,循环直至访问完所有顶点
while (que.length) { while (que.length) {
const vet = que.shift(); // 队首顶点出队 const vet = que.shift(); // 队首顶点出队
res.push(vet); // 记录访问顶点 res.push(vet); // 记录访问顶点
// 遍历该顶点的所有邻接顶点 // 遍历该顶点的所有邻接顶点
for (const adjVet of graph.adjList.get(vet) ?? []) { for (const adjVet of graph.adjList.get(vet) ?? []) {
if (visited.has(adjVet)) { if (visited.has(adjVet)) {
continue; // 跳过已被访问过的顶点 continue; // 跳过已被访问过的顶点
} }
que.push(adjVet); // 只入队未访问 que.push(adjVet); // 只入队未访问
visited.add(adjVet); // 标记该顶点已被访问 visited.add(adjVet); // 标记该顶点已被访问
} }
} }
// 返回顶点遍历序列 // 返回顶点遍历序列
return res; return res;
} }
/* Driver Code */ /* Driver Code */
/* 初始化无向图 */ /* 初始化无向图 */
const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const edges = [[v[0], v[1]], [v[0], v[3]], [v[1], v[2]], [v[1], v[4]], const edges = [
[v[2], v[5]], [v[3], v[4]], [v[3], v[6]], [v[4], v[5]], [v[0], v[1]],
[v[4], v[7]], [v[5], v[8]], [v[6], v[7]], [v[7], v[8]]]; [v[0], v[3]],
[v[1], v[2]],
[v[1], v[4]],
[v[2], v[5]],
[v[3], v[4]],
[v[3], v[6]],
[v[4], v[5]],
[v[4], v[7]],
[v[5], v[8]],
[v[6], v[7]],
[v[7], v[8]]
];
const graph = new GraphAdjList(edges); const graph = new GraphAdjList(edges);
console.log("\n初始化后图为"); console.log('\n初始化后图为');
graph.print(); graph.print();
/* 广度优先遍历 BFS */ /* 广度优先遍历 BFS */
const res = graphBFS(graph, v[0]); const res = graphBFS(graph, v[0]);
console.log("\n广度优先遍历BFS顶点序列为"); console.log('\n广度优先遍历BFS顶点序列为');
console.log(Vertex.vetsToVals(res)); console.log(Vertex.vetsToVals(res));

View File

@ -4,14 +4,13 @@
* Author: Zhuo Qinyue (1403450829@qq.com) * Author: Zhuo Qinyue (1403450829@qq.com)
*/ */
import { Vertex } from '../modules/Vertex';
import { Vertex } from '../module/Vertex';
import { GraphAdjList } from './graph_adjacency_list'; import { GraphAdjList } from './graph_adjacency_list';
/* 深度优先遍历 DFS 辅助函数 */ /* 深度优先遍历 DFS 辅助函数 */
function dfs(graph: GraphAdjList, visited: Set<Vertex>, res: Vertex[], vet: Vertex): void { function dfs(graph: GraphAdjList, visited: Set<Vertex>, res: Vertex[], vet: Vertex): void {
res.push(vet); // 记录访问顶点 res.push(vet); // 记录访问顶点
visited.add(vet); // 标记该顶点已被访问 visited.add(vet); // 标记该顶点已被访问
// 遍历该顶点的所有邻接顶点 // 遍历该顶点的所有邻接顶点
for (const adjVet of graph.adjList.get(vet)) { for (const adjVet of graph.adjList.get(vet)) {
if (visited.has(adjVet)) { if (visited.has(adjVet)) {
@ -33,17 +32,22 @@ function graphDFS(graph: GraphAdjList, startVet: Vertex): Vertex[] {
return res; return res;
} }
/* Driver Code */ /* Driver Code */
/* 初始化无向图 */ /* 初始化无向图 */
const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6]); const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6]);
const edges = [[v[0], v[1]], [v[0], v[3]], [v[1], v[2]], const edges = [
[v[2], v[5]], [v[4], v[5]], [v[5], v[6]]]; [v[0], v[1]],
[v[0], v[3]],
[v[1], v[2]],
[v[2], v[5]],
[v[4], v[5]],
[v[5], v[6]]
];
const graph = new GraphAdjList(edges); const graph = new GraphAdjList(edges);
console.log("\n初始化后图为"); console.log('\n初始化后图为');
graph.print(); graph.print();
/* 深度优先遍历 DFS */ /* 深度优先遍历 DFS */
const res = graphDFS(graph, v[0]); const res = graphDFS(graph, v[0]);
console.log("\n深度优先遍历DFS顶点序列为"); console.log('\n深度优先遍历DFS顶点序列为');
console.log(Vertex.vetsToVals(res)); console.log(Vertex.vetsToVals(res));

View File

@ -3,8 +3,8 @@
* Created Time: 2023-02-07 * Created Time: 2023-02-07
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
import { printHeap } from "../module/PrintUtil"; import { printHeap } from '../modules/PrintUtil';
/* 最大堆类 */ /* 最大堆类 */
class MaxHeap { class MaxHeap {
@ -83,7 +83,7 @@ class MaxHeap {
/* 元素出堆 */ /* 元素出堆 */
public poll(): number { public poll(): number {
// 判空处理 // 判空处理
if (this.isEmpty()) throw new RangeError("Heap is empty."); if (this.isEmpty()) throw new RangeError('Heap is empty.');
// 交换根结点与最右叶结点(即交换首元素与尾元素) // 交换根结点与最右叶结点(即交换首元素与尾元素)
this.swap(0, this.size() - 1); this.swap(0, this.size() - 1);
// 删除结点 // 删除结点
@ -98,7 +98,8 @@ class MaxHeap {
private siftDown(i: number): void { private siftDown(i: number): void {
while (true) { while (true) {
// 判断结点 i, l, r 中值最大的结点,记为 ma // 判断结点 i, l, r 中值最大的结点,记为 ma
const l = this.left(i), r = this.right(i); const l = this.left(i),
r = this.right(i);
let ma = i; let ma = i;
if (l < this.size() && this.maxHeap[l] > this.maxHeap[ma]) ma = l; if (l < this.size() && this.maxHeap[l] > this.maxHeap[ma]) ma = l;
if (r < this.size() && this.maxHeap[r] > this.maxHeap[ma]) ma = r; if (r < this.size() && this.maxHeap[r] > this.maxHeap[ma]) ma = r;
@ -117,7 +118,6 @@ class MaxHeap {
} }
} }
function testPush(maxHeap: MaxHeap, val: number): void { function testPush(maxHeap: MaxHeap, val: number): void {
maxHeap.push(val); // 元素入堆 maxHeap.push(val); // 元素入堆
console.log(`\n添加元素 ${val}`); console.log(`\n添加元素 ${val}`);
@ -133,7 +133,7 @@ function testPoll(maxHeap: MaxHeap): void {
/* Driver Code */ /* Driver Code */
/* 初始化大顶堆 */ /* 初始化大顶堆 */
const maxHeap = new MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]); const maxHeap = new MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
console.log("\n输入列表并建堆后"); console.log('\n输入列表并建堆后');
maxHeap.print(); maxHeap.print();
/* 获取堆顶元素 */ /* 获取堆顶元素 */

View File

@ -10,7 +10,7 @@ function binarySearch(nums: number[], target: number): number {
let i = 0, j = nums.length - 1; let i = 0, j = nums.length - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空) // 循环,当搜索区间为空时跳出(当 i > j 时为空)
while (i <= j) { while (i <= j) {
const m = Math.floor(i + (j - i) / 2); // 计算中点索引 m const m = Math.floor((i + j) / 2); // 计算中点索引 m
if (nums[m] < target) { // 此情况说明 target 在区间 [m+1, j] 中 if (nums[m] < target) { // 此情况说明 target 在区间 [m+1, j] 中
i = m + 1; i = m + 1;
} else if (nums[m] > target) { // 此情况说明 target 在区间 [i, m-1] 中 } else if (nums[m] > target) { // 此情况说明 target 在区间 [i, m-1] 中
@ -28,7 +28,7 @@ function binarySearch1(nums: number[], target: number): number {
let i = 0, j = nums.length; let i = 0, j = nums.length;
// 循环,当搜索区间为空时跳出(当 i = j 时为空) // 循环,当搜索区间为空时跳出(当 i = j 时为空)
while (i < j) { while (i < j) {
const m = Math.floor(i + (j - i) / 2); // 计算中点索引 m const m = Math.floor((i + j) / 2); // 计算中点索引 m
if (nums[m] < target) { // 此情况说明 target 在区间 [m+1, j) 中 if (nums[m] < target) { // 此情况说明 target 在区间 [m+1, j) 中
i = m + 1; i = m + 1;
} else if (nums[m] > target) { // 此情况说明 target 在区间 [i, m) 中 } else if (nums[m] > target) { // 此情况说明 target 在区间 [i, m) 中

View File

@ -4,25 +4,22 @@
* Author: Zhuo Qinyue (1403450829@qq.com) * Author: Zhuo Qinyue (1403450829@qq.com)
*/ */
import { printLinkedList } from "../module/PrintUtil"; import { ListNode, arrToLinkedList } from '../modules/ListNode';
import { ListNode, arrToLinkedList } from "../module/ListNode";
/* 哈希查找(数组) */ /* 哈希查找(数组) */
function hashingSearchArray(map: Map<number, number>, target: number): number { function hashingSearchArray(map: Map<number, number>, target: number): number {
// 哈希表的 key: 目标元素value: 索引 // 哈希表的 key: 目标元素value: 索引
// 若哈希表中无此 key ,返回 -1 // 若哈希表中无此 key ,返回 -1
return map.has(target) ? map.get(target) as number : -1; return map.has(target) ? (map.get(target) as number) : -1;
} }
/* 哈希查找(链表) */ /* 哈希查找(链表) */
function hashingSearchLinkedList(map: Map<number, ListNode>, target: number): ListNode | null { function hashingSearchLinkedList(map: Map<number, ListNode>, target: number): ListNode | null {
// 哈希表的 key: 目标结点值value: 结点对象 // 哈希表的 key: 目标结点值value: 结点对象
// 若哈希表中无此 key ,返回 null // 若哈希表中无此 key ,返回 null
return map.has(target) ? map.get(target) as ListNode : null; return map.has(target) ? (map.get(target) as ListNode) : null;
} }
/* Driver Code */ /* Driver Code */
const target = 3; const target = 3;
@ -31,20 +28,20 @@ const nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
// 初始化哈希表 // 初始化哈希表
const map = new Map(); const map = new Map();
for (let i = 0; i < nums.length; i++) { for (let i = 0; i < nums.length; i++) {
map.set(nums[i], i); // key: 元素value: 索引 map.set(nums[i], i); // key: 元素value: 索引
} }
const index = hashingSearchArray(map, target); const index = hashingSearchArray(map, target);
console.log("目标元素 3 的索引 = " + index); console.log('目标元素 3 的索引 = ' + index);
/* 哈希查找(链表) */ /* 哈希查找(链表) */
let head = arrToLinkedList(nums) let head = arrToLinkedList(nums);
// 初始化哈希表 // 初始化哈希表
const map1 = new Map(); const map1 = new Map();
while (head != null) { while (head != null) {
map1.set(head.val, head); // key: 结点值value: 结点 map1.set(head.val, head); // key: 结点值value: 结点
head = head.next; head = head.next;
} }
const node = hashingSearchLinkedList(map1, target); const node = hashingSearchLinkedList(map1, target);
console.log("目标结点值 3 的对应结点对象为", node); console.log('目标结点值 3 的对应结点对象为', node);
export {}; export {};

View File

@ -4,7 +4,7 @@
* Author: Daniel (better.sunjian@gmail.com) * Author: Daniel (better.sunjian@gmail.com)
*/ */
import { ListNode, arrToLinkedList } from '../module/ListNode'; import { ListNode, arrToLinkedList } from '../modules/ListNode';
/* 线性查找(数组)*/ /* 线性查找(数组)*/
function linearSearchArray(nums: number[], target: number): number { function linearSearchArray(nums: number[], target: number): number {

View File

@ -1,5 +1,5 @@
/** /**
* File: quick_sort.ts * File: bubble_sort.ts
* Created Time: 2022-12-12 * Created Time: 2022-12-12
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */

View File

@ -1,5 +1,5 @@
/** /**
* File: quick_sort.ts * File: insertion_sort.ts
* Created Time: 2022-12-12 * Created Time: 2022-12-12
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */

View File

@ -1,5 +1,5 @@
/** /**
* File: quick_sort.ts * File: merge_sort.ts
* Created Time: 2022-12-12 * Created Time: 2022-12-12
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */

View File

@ -71,6 +71,7 @@ class ArrayQueue {
} }
} }
/* Driver Code */
/* 初始化队列 */ /* 初始化队列 */
const capacity = 10; const capacity = 10;
const queue = new ArrayQueue(capacity); const queue = new ArrayQueue(capacity);

View File

@ -49,7 +49,6 @@ class ArrayStack {
/* Driver Code */ /* Driver Code */
/* 初始化栈 */ /* 初始化栈 */
const stack = new ArrayStack(); const stack = new ArrayStack();

View File

@ -4,6 +4,7 @@
* Author: Zhuo Qinyue (1403450829@qq.com) * Author: Zhuo Qinyue (1403450829@qq.com)
*/ */
/* Driver Code */
/* 初始化双向队列 */ /* 初始化双向队列 */
// TypeScript 没有内置的双端队列,只能把 Array 当作双端队列来使用 // TypeScript 没有内置的双端队列,只能把 Array 当作双端队列来使用
const deque: number[] = []; const deque: number[] = [];

View File

@ -19,21 +19,21 @@ class ListNode {
/* 基于双向链表实现的双向队列 */ /* 基于双向链表实现的双向队列 */
class LinkedListDeque { class LinkedListDeque {
front: ListNode; // 头结点 front private front: ListNode; // 头结点 front
rear: ListNode; // 尾结点 rear private rear: ListNode; // 尾结点 rear
len: number; // 双向队列的长度 private queSize: number; // 双向队列的长度
constructor() { constructor() {
this.front = null; this.front = null;
this.rear = null; this.rear = null;
this.len = 0; this.queSize = 0;
} }
/* 队尾入队操作 */ /* 队尾入队操作 */
pushLast(val: number): void { pushLast(val: number): void {
const node: ListNode = new ListNode(val); const node: ListNode = new ListNode(val);
// 若链表为空,则令 front, rear 都指向 node // 若链表为空,则令 front, rear 都指向 node
if (this.len === 0) { if (this.queSize === 0) {
this.front = node; this.front = node;
this.rear = node; this.rear = node;
} else { } else {
@ -42,14 +42,14 @@ class LinkedListDeque {
node.prev = this.rear; node.prev = this.rear;
this.rear = node; // 更新尾结点 this.rear = node; // 更新尾结点
} }
this.len++; this.queSize++;
} }
/* 队首入队操作 */ /* 队首入队操作 */
pushFirst(val: number): void { pushFirst(val: number): void {
const node: ListNode = new ListNode(val); const node: ListNode = new ListNode(val);
// 若链表为空,则令 front, rear 都指向 node // 若链表为空,则令 front, rear 都指向 node
if (this.len === 0) { if (this.queSize === 0) {
this.front = node; this.front = node;
this.rear = node; this.rear = node;
} else { } else {
@ -58,12 +58,12 @@ class LinkedListDeque {
node.next = this.front; node.next = this.front;
this.front = node; // 更新头结点 this.front = node; // 更新头结点
} }
this.len++; this.queSize++;
} }
/* 队尾出队操作 */ /* 队尾出队操作 */
pollLast(): number { pollLast(): number {
if (this.len === 0) { if (this.queSize === 0) {
return null; return null;
} }
const value: number = this.rear.val; // 存储尾结点值 const value: number = this.rear.val; // 存储尾结点值
@ -74,13 +74,13 @@ class LinkedListDeque {
this.rear.prev = null; this.rear.prev = null;
} }
this.rear = temp; // 更新尾结点 this.rear = temp; // 更新尾结点
this.len--; this.queSize--;
return value; return value;
} }
/* 队首出队操作 */ /* 队首出队操作 */
pollFirst(): number { pollFirst(): number {
if (this.len === 0) { if (this.queSize === 0) {
return null; return null;
} }
const value: number = this.front.val; // 存储尾结点值 const value: number = this.front.val; // 存储尾结点值
@ -91,28 +91,28 @@ class LinkedListDeque {
this.front.next = null; this.front.next = null;
} }
this.front = temp; // 更新头结点 this.front = temp; // 更新头结点
this.len--; this.queSize--;
return value; return value;
} }
/* 访问队尾元素 */ /* 访问队尾元素 */
peekLast(): number { peekLast(): number {
return this.len === 0 ? null : this.rear.val; return this.queSize === 0 ? null : this.rear.val;
} }
/* 访问队首元素 */ /* 访问队首元素 */
peekFirst(): number { peekFirst(): number {
return this.len === 0 ? null : this.front.val; return this.queSize === 0 ? null : this.front.val;
} }
/* 获取双向队列的长度 */ /* 获取双向队列的长度 */
size(): number { size(): number {
return this.len; return this.queSize;
} }
/* 判断双向队列是否为空 */ /* 判断双向队列是否为空 */
isEmpty(): boolean { isEmpty(): boolean {
return this.len === 0; return this.queSize === 0;
} }
/* 打印双向队列 */ /* 打印双向队列 */
@ -127,6 +127,7 @@ class LinkedListDeque {
} }
} }
/* Driver Code */
/* 初始化双向队列 */ /* 初始化双向队列 */
const linkedListDeque: LinkedListDeque = new LinkedListDeque(); const linkedListDeque: LinkedListDeque = new LinkedListDeque();
linkedListDeque.pushLast(3); linkedListDeque.pushLast(3);

View File

@ -4,12 +4,12 @@
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com) * Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/ */
import { ListNode } from "../module/ListNode" import { ListNode } from '../modules/ListNode';
/* 基于链表实现的队列 */ /* 基于链表实现的队列 */
class LinkedListQueue { class LinkedListQueue {
private front: ListNode | null; // 头结点 front private front: ListNode | null; // 头结点 front
private rear: ListNode | null; // 尾结点 rear private rear: ListNode | null; // 尾结点 rear
private queSize: number = 0; private queSize: number = 0;
constructor() { constructor() {
@ -46,8 +46,7 @@ class LinkedListQueue {
/* 出队 */ /* 出队 */
poll(): number { poll(): number {
const num = this.peek(); const num = this.peek();
if (!this.front) if (!this.front) throw new Error('队列为空');
throw new Error("队列为空")
// 删除头结点 // 删除头结点
this.front = this.front.next; this.front = this.front.next;
this.queSize--; this.queSize--;
@ -56,8 +55,7 @@ class LinkedListQueue {
/* 访问队首元素 */ /* 访问队首元素 */
peek(): number { peek(): number {
if (this.size === 0) if (this.size === 0) throw new Error('队列为空');
throw new Error("队列为空");
return this.front!.val; return this.front!.val;
} }
@ -73,7 +71,7 @@ class LinkedListQueue {
} }
} }
/* Driver Code */
/* 初始化队列 */ /* 初始化队列 */
const queue = new LinkedListQueue(); const queue = new LinkedListQueue();
@ -83,22 +81,22 @@ queue.push(3);
queue.push(2); queue.push(2);
queue.push(5); queue.push(5);
queue.push(4); queue.push(4);
console.log("队列 queue = " + queue.toArray()); console.log('队列 queue = ' + queue.toArray());
/* 访问队首元素 */ /* 访问队首元素 */
const peek = queue.peek(); const peek = queue.peek();
console.log("队首元素 peek = " + peek); console.log('队首元素 peek = ' + peek);
/* 元素出队 */ /* 元素出队 */
const poll = queue.poll(); const poll = queue.poll();
console.log("出队元素 poll = " + poll + ",出队后 queue = " + queue.toArray()); console.log('出队元素 poll = ' + poll + ',出队后 queue = ' + queue.toArray());
/* 获取队列的长度 */ /* 获取队列的长度 */
const size = queue.size; const size = queue.size;
console.log("队列长度 size = " + size); console.log('队列长度 size = ' + size);
/* 判断队列是否为空 */ /* 判断队列是否为空 */
const isEmpty = queue.isEmpty(); const isEmpty = queue.isEmpty();
console.log("队列是否为空 = " + isEmpty); console.log('队列是否为空 = ' + isEmpty);
export {}; export {};

View File

@ -4,12 +4,12 @@
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com) * Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/ */
import { ListNode } from "../module/ListNode" import { ListNode } from '../modules/ListNode';
/* 基于链表实现的栈 */ /* 基于链表实现的栈 */
class LinkedListStack { class LinkedListStack {
private stackPeek: ListNode | null; // 将头结点作为栈顶 private stackPeek: ListNode | null; // 将头结点作为栈顶
private stkSize: number = 0; // 栈的长度 private stkSize: number = 0; // 栈的长度
constructor() { constructor() {
this.stackPeek = null; this.stackPeek = null;
@ -36,8 +36,7 @@ class LinkedListStack {
/* 出栈 */ /* 出栈 */
pop(): number { pop(): number {
const num = this.peek(); const num = this.peek();
if (!this.stackPeek) if (!this.stackPeek) throw new Error('栈为空');
throw new Error("栈为空");
this.stackPeek = this.stackPeek.next; this.stackPeek = this.stackPeek.next;
this.stkSize--; this.stkSize--;
return num; return num;
@ -45,8 +44,7 @@ class LinkedListStack {
/* 访问栈顶元素 */ /* 访问栈顶元素 */
peek(): number { peek(): number {
if (!this.stackPeek) if (!this.stackPeek) throw new Error('栈为空');
throw new Error("栈为空");
return this.stackPeek.val; return this.stackPeek.val;
} }
@ -62,7 +60,7 @@ class LinkedListStack {
} }
} }
/* Driver Code */
/* 初始化栈 */ /* 初始化栈 */
const stack = new LinkedListStack(); const stack = new LinkedListStack();
@ -72,22 +70,22 @@ stack.push(3);
stack.push(2); stack.push(2);
stack.push(5); stack.push(5);
stack.push(4); stack.push(4);
console.log("栈 stack = " + stack.toArray()); console.log('栈 stack = ' + stack.toArray());
/* 访问栈顶元素 */ /* 访问栈顶元素 */
const peek = stack.peek(); const peek = stack.peek();
console.log("栈顶元素 peek = " + peek); console.log('栈顶元素 peek = ' + peek);
/* 元素出栈 */ /* 元素出栈 */
const pop = stack.pop(); const pop = stack.pop();
console.log("出栈元素 pop = " + pop + ",出栈后 stack = " + stack.toArray()); console.log('出栈元素 pop = ' + pop + ',出栈后 stack = ' + stack.toArray());
/* 获取栈的长度 */ /* 获取栈的长度 */
const size = stack.size; const size = stack.size;
console.log("栈的长度 size = " + size); console.log('栈的长度 size = ' + size);
/* 判断是否为空 */ /* 判断是否为空 */
const isEmpty = stack.isEmpty(); const isEmpty = stack.isEmpty();
console.log("栈是否为空 = " + isEmpty); console.log('栈是否为空 = ' + isEmpty);
export {}; export {};

View File

@ -4,6 +4,7 @@
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com) * Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/ */
/* Driver Code */
/* 初始化队列 */ /* 初始化队列 */
// TypeScript 没有内置的队列,可以把 Array 当作队列来使用 // TypeScript 没有内置的队列,可以把 Array 当作队列来使用
const queue: number[] = []; const queue: number[] = [];
@ -14,18 +15,23 @@ queue.push(3);
queue.push(2); queue.push(2);
queue.push(5); queue.push(5);
queue.push(4); queue.push(4);
console.log("队列 queue =", queue);
/* 访问队首元素 */ /* 访问队首元素 */
const peek = queue[0]; const peek = queue[0];
console.log("队首元素 peek =", peek);
/* 元素出队 */ /* 元素出队 */
// 底层是数组,因此 shift() 方法的时间复杂度为 O(n) // 底层是数组,因此 shift() 方法的时间复杂度为 O(n)
const poll = queue.shift(); const poll = queue.shift();
console.log("出队元素 poll =", poll, ",出队后 queue = ", queue);
/* 获取队列的长度 */ /* 获取队列的长度 */
const size = queue.length; const size = queue.length;
console.log("队列长度 size =", size);
/* 判断队列是否为空 */ /* 判断队列是否为空 */
const empty = queue.length === 0; const isEmpty = queue.length === 0;
console.log("队列是否为空 = ", isEmpty);
export {}; export {};

View File

@ -4,6 +4,7 @@
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com) * Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/ */
/* Driver Code */
/* 初始化栈 */ /* 初始化栈 */
// Typescript 没有内置的栈类,可以把 Array 当作栈来使用 // Typescript 没有内置的栈类,可以把 Array 当作栈来使用
const stack: number[] = []; const stack: number[] = [];
@ -14,17 +15,23 @@ stack.push(3);
stack.push(2); stack.push(2);
stack.push(5); stack.push(5);
stack.push(4); stack.push(4);
console.log("栈 stack =", stack);
/* 访问栈顶元素 */ /* 访问栈顶元素 */
const peek = stack[stack.length - 1]; const peek = stack[stack.length - 1];
console.log("栈顶元素 peek =", peek);
/* 元素出栈 */ /* 元素出栈 */
const pop = stack.pop(); const pop = stack.pop();
console.log("出栈元素 pop =", pop);
console.log("出栈后 stack =", stack);
/* 获取栈的长度 */ /* 获取栈的长度 */
const size = stack.length; const size = stack.length;
console.log("栈的长度 size =", size);
/* 判断是否为空 */ /* 判断是否为空 */
const is_empty = stack.length === 0; const isEmpty = stack.length === 0;
console.log("栈是否为空 =", isEmpty);
export {}; export {};

View File

@ -4,8 +4,8 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
import { TreeNode } from "../module/TreeNode"; import { TreeNode } from '../modules/TreeNode';
import { printTree } from "../module/PrintUtil"; import { printTree } from '../modules/PrintUtil';
/* AVL 树*/ /* AVL 树*/
class AVLTree { class AVLTree {
@ -22,7 +22,7 @@ class AVLTree {
} }
/* 更新结点高度 */ /* 更新结点高度 */
updateHeight(node: TreeNode): void { private updateHeight(node: TreeNode): void {
// 结点高度等于最高子树高度 + 1 // 结点高度等于最高子树高度 + 1
node.height = Math.max(this.height(node.left), this.height(node.right)) + 1; node.height = Math.max(this.height(node.left), this.height(node.right)) + 1;
} }
@ -36,7 +36,7 @@ class AVLTree {
} }
/* 右旋操作 */ /* 右旋操作 */
rightRotate(node: TreeNode): TreeNode { private rightRotate(node: TreeNode): TreeNode {
const child = node.left; const child = node.left;
const grandChild = child.right; const grandChild = child.right;
// 以 child 为原点,将 node 向右旋转 // 以 child 为原点,将 node 向右旋转
@ -50,7 +50,7 @@ class AVLTree {
} }
/* 左旋操作 */ /* 左旋操作 */
leftRotate(node: TreeNode): TreeNode { private leftRotate(node: TreeNode): TreeNode {
const child = node.right; const child = node.right;
const grandChild = child.left; const grandChild = child.left;
// 以 child 为原点,将 node 向左旋转 // 以 child 为原点,将 node 向左旋转
@ -64,7 +64,7 @@ class AVLTree {
} }
/* 执行旋转操作,使该子树重新恢复平衡 */ /* 执行旋转操作,使该子树重新恢复平衡 */
rotate(node: TreeNode): TreeNode { private rotate(node: TreeNode): TreeNode {
// 获取结点 node 的平衡因子 // 获取结点 node 的平衡因子
const balanceFactor = this.balanceFactor(node); const balanceFactor = this.balanceFactor(node);
// 左偏树 // 左偏树
@ -100,7 +100,7 @@ class AVLTree {
} }
/* 递归插入结点(辅助方法) */ /* 递归插入结点(辅助方法) */
insertHelper(node: TreeNode, val: number): TreeNode { private insertHelper(node: TreeNode, val: number): TreeNode {
if (node === null) return new TreeNode(val); if (node === null) return new TreeNode(val);
/* 1. 查找插入位置,并插入结点 */ /* 1. 查找插入位置,并插入结点 */
if (val < node.val) { if (val < node.val) {
@ -124,7 +124,7 @@ class AVLTree {
} }
/* 递归删除结点(辅助方法) */ /* 递归删除结点(辅助方法) */
removeHelper(node: TreeNode, val: number): TreeNode { private removeHelper(node: TreeNode, val: number): TreeNode {
if (node === null) return null; if (node === null) return null;
/* 1. 查找结点,并删除之 */ /* 1. 查找结点,并删除之 */
if (val < node.val) { if (val < node.val) {
@ -139,7 +139,7 @@ class AVLTree {
return null; return null;
} else { } else {
// 子结点数量 = 1 ,直接删除 node // 子结点数量 = 1 ,直接删除 node
node = child; node = child;
} }
} else { } else {
// 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点 // 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点
@ -156,7 +156,7 @@ class AVLTree {
} }
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */ /* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
getInOrderNext(node: TreeNode): TreeNode { private getInOrderNext(node: TreeNode): TreeNode {
if (node === null) return node; if (node === null) return node;
// 循环访问左子结点,直到叶结点时为最小结点,跳出 // 循环访问左子结点,直到叶结点时为最小结点,跳出
while (node.left !== null) { while (node.left !== null) {
@ -188,13 +188,13 @@ class AVLTree {
function testInsert(tree: AVLTree, val: number): void { function testInsert(tree: AVLTree, val: number): void {
tree.insert(val); tree.insert(val);
console.log("\n插入结点 " + val + " 后AVL 树为"); console.log('\n插入结点 ' + val + ' 后AVL 树为');
printTree(tree.root); printTree(tree.root);
} }
function testRemove(tree: AVLTree, val: number): void { function testRemove(tree: AVLTree, val: number): void {
tree.remove(val); tree.remove(val);
console.log("\n删除结点 " + val + " 后AVL 树为"); console.log('\n删除结点 ' + val + ' 后AVL 树为');
printTree(tree.root); printTree(tree.root);
} }
@ -225,4 +225,4 @@ testRemove(avlTree, 4); // 删除度为 2 的结点
/* 查询结点 */ /* 查询结点 */
const node = avlTree.search(7); const node = avlTree.search(7);
console.log("\n查找到的结点对象为", node, ",结点值 = " + node.val); console.log('\n查找到的结点对象为', node, ',结点值 = ' + node.val);

View File

@ -4,8 +4,8 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
import { TreeNode } from '../module/TreeNode'; import { TreeNode } from '../modules/TreeNode';
import { printTree } from '../module/PrintUtil'; import { printTree } from '../modules/PrintUtil';
/* 二叉搜索树 */ /* 二叉搜索树 */
let root: TreeNode | null; let root: TreeNode | null;

View File

@ -4,8 +4,8 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
import { TreeNode } from '../module/TreeNode'; import { TreeNode } from '../modules/TreeNode';
import { printTree } from '../module/PrintUtil'; import { printTree } from '../modules/PrintUtil';
/* 初始化二叉树 */ /* 初始化二叉树 */
// 初始化结点 // 初始化结点

View File

@ -4,9 +4,9 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
import { type TreeNode } from '../module/TreeNode'; import { type TreeNode } from '../modules/TreeNode';
import { arrToTree } from '../module/TreeNode'; import { arrToTree } from '../modules/TreeNode';
import { printTree } from '../module/PrintUtil'; import { printTree } from '../modules/PrintUtil';
/* 层序遍历 */ /* 层序遍历 */
function levelOrder(root: TreeNode | null): number[] { function levelOrder(root: TreeNode | null): number[] {
@ -30,7 +30,7 @@ function levelOrder(root: TreeNode | null): number[] {
/* Driver Code */ /* Driver Code */
/* 初始化二叉树 */ /* 初始化二叉树 */
// 这里借助了一个从数组直接生成二叉树的函数 // 这里借助了一个从数组直接生成二叉树的函数
var root = arrToTree([1, 2, 3, 4, 5, 6, 7]); const root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
console.log('\n初始化二叉树\n'); console.log('\n初始化二叉树\n');
printTree(root); printTree(root);

View File

@ -4,9 +4,9 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
import { type TreeNode } from '../module/TreeNode'; import { type TreeNode } from '../modules/TreeNode';
import { arrToTree } from '../module/TreeNode'; import { arrToTree } from '../modules/TreeNode';
import { printTree } from '../module/PrintUtil'; import { printTree } from '../modules/PrintUtil';
// 初始化列表,用于存储遍历序列 // 初始化列表,用于存储遍历序列
const list: number[] = []; const list: number[] = [];

View File

@ -49,4 +49,7 @@ function arrToTree(arr: (number | null)[]): TreeNode | null {
return root; return root;
} }
export { TreeNode, arrToTree }; export {
TreeNode,
arrToTree
};

View File

@ -31,4 +31,6 @@ class Vertex {
} }
} }
export { Vertex }; export {
Vertex
};