This commit is contained in:
krahets 2023-02-07 17:17:14 +08:00
parent ecbf2d1560
commit 1ca5c731f7
19 changed files with 501 additions and 192 deletions

View File

@ -122,6 +122,7 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
// 在区间 [0, nums.length) 中随机抽取一个数字 // 在区间 [0, nums.length) 中随机抽取一个数字
int randomIndex = ThreadLocalRandom.current(). int randomIndex = ThreadLocalRandom.current().
nextInt(0, nums.length); nextInt(0, nums.length);
// 获取并返回随机元素
int randomNum = nums[randomIndex]; int randomNum = nums[randomIndex];
return randomNum; return randomNum;
} }

View File

@ -801,6 +801,17 @@ comments: true
// 更新列表容量 // 更新列表容量
capacity = nums.length; capacity = nums.length;
} }
/* 将列表转换为数组 */
public int[] toArray() {
int size = size();
// 仅转换有效长度范围内的列表元素
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
nums[i] = get(i);
}
return nums;
}
} }
``` ```

View File

@ -1094,7 +1094,7 @@ $$
/* 平方阶 */ /* 平方阶 */
void quadratic(int n) { void quadratic(int n) {
// 矩阵占用 O(n^2) 空间 // 矩阵占用 O(n^2) 空间
int [][]numMatrix = new int[n][n]; int[][] numMatrix = new int[n][n];
// 二维列表占用 O(n^2) 空间 // 二维列表占用 O(n^2) 空间
List<List<Integer>> numList = new ArrayList<>(); List<List<Integer>> numList = new ArrayList<>();
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
@ -1253,6 +1253,7 @@ $$
if (n <= 0) return 0; if (n <= 0) return 0;
// 数组 nums 长度为 n, n-1, ..., 2, 1 // 数组 nums 长度为 n, n-1, ..., 2, 1
int[] nums = new int[n]; int[] nums = new int[n];
System.out.println("递归 n = " + n + " 中的 nums 长度 = " + nums.length);
return quadraticRecur(n - 1); return quadraticRecur(n - 1);
} }
``` ```

View File

@ -33,6 +33,7 @@ comments: true
=== "Java" === "Java"
```java title="leetcode_two_sum.java" ```java title="leetcode_two_sum.java"
/* 方法一:暴力枚举 */
class SolutionBruteForce { class SolutionBruteForce {
public int[] twoSum(int[] nums, int target) { public int[] twoSum(int[] nums, int target) {
int size = nums.length; int size = nums.length;
@ -207,6 +208,7 @@ comments: true
=== "Java" === "Java"
```java title="leetcode_two_sum.java" ```java title="leetcode_two_sum.java"
/* 方法二:辅助哈希表 */
class SolutionHashMap { class SolutionHashMap {
public int[] twoSum(int[] nums, int target) { public int[] twoSum(int[] nums, int target) {
int size = nums.length; int size = nums.length;

View File

@ -2524,7 +2524,6 @@ $$
=== "Java" === "Java"
```java title="worst_best_time_complexity.java" ```java title="worst_best_time_complexity.java"
public class worst_best_time_complexity {
/* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */ /* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */
int[] randomNumbers(int n) { int[] randomNumbers(int n) {
Integer[] nums = new Integer[n]; Integer[] nums = new Integer[n];
@ -2552,7 +2551,6 @@ $$
} }
return -1; return -1;
} }
}
``` ```
=== "C++" === "C++"
@ -2640,7 +2638,7 @@ $$
```js title="worst_best_time_complexity.js" ```js title="worst_best_time_complexity.js"
/* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */ /* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */
function randomNumbers(n) { function randomNumbers(n) {
let nums = Array(n); const nums = Array(n);
// 生成数组 nums = { 1, 2, 3, ..., n } // 生成数组 nums = { 1, 2, 3, ..., n }
for (let i = 0; i < n; i++) { for (let i = 0; i < n; i++) {
nums[i] = i + 1; nums[i] = i + 1;
@ -2673,15 +2671,15 @@ $$
```typescript title="worst_best_time_complexity.ts" ```typescript title="worst_best_time_complexity.ts"
/* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */ /* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */
function randomNumbers(n: number): number[] { function randomNumbers(n: number): number[] {
let nums = Array(n); const nums = Array(n);
// 生成数组 nums = { 1, 2, 3, ..., n } // 生成数组 nums = { 1, 2, 3, ..., n }
for (let i = 0; i < n; i++) { for (let i = 0; i < n; i++) {
nums[i] = i + 1; nums[i] = i + 1;
} }
// 随机打乱数组元素 // 随机打乱数组元素
for (let i = 0; i < n; i++) { for (let i = 0; i < n; i++) {
let r = Math.floor(Math.random() * (i + 1)); const r = Math.floor(Math.random() * (i + 1));
let temp = nums[i]; const temp = nums[i];
nums[i] = nums[r]; nums[i] = nums[r];
nums[r] = temp; nums[r] = temp;
} }

View File

@ -111,6 +111,14 @@ comments: true
adjMat.get(i).set(j, 0); adjMat.get(i).set(j, 0);
adjMat.get(j).set(i, 0); adjMat.get(j).set(i, 0);
} }
/* 打印邻接矩阵 */
public void print() {
System.out.print("顶点列表 = ");
System.out.println(vertices);
System.out.println("邻接矩阵 =");
PrintUtil.printMatrix(adjMat);
}
} }
``` ```
@ -423,6 +431,17 @@ comments: true
set.remove(vet); set.remove(vet);
} }
} }
/* 打印邻接表 */
public void print() {
System.out.println("邻接表 =");
for (Map.Entry<Vertex, Set<Vertex>> entry : adjList.entrySet()) {
List<Integer> tmp = new ArrayList<>();
for (Vertex vertex : entry.getValue())
tmp.add(vertex.val);
System.out.println(entry.getKey().val + ": " + tmp + ",");
}
}
} }
``` ```

View File

@ -418,8 +418,8 @@ $$
```java title="array_hash_map.java" ```java title="array_hash_map.java"
/* 键值对 int->String */ /* 键值对 int->String */
class Entry { class Entry {
public int key; // 键 public int key;
public String val; // 值 public String val;
public Entry(int key, String val) { public Entry(int key, String val) {
this.key = key; this.key = key;
this.val = val; this.val = val;
@ -461,9 +461,46 @@ $$
/* 删除操作 */ /* 删除操作 */
public void remove(int key) { public void remove(int key) {
int index = hashFunc(key); int index = hashFunc(key);
// 置为 null代表删除 // 置为 null ,代表删除
bucket.set(index, null); bucket.set(index, null);
} }
/* 获取所有键值对 */
public List<Entry> entrySet() {
List<Entry> entrySet = new ArrayList<>();
for (Entry pair : bucket) {
if (pair != null)
entrySet.add(pair);
}
return entrySet;
}
/* 获取所有键 */
public List<Integer> keySet() {
List<Integer> keySet = new ArrayList<>();
for (Entry pair : bucket) {
if (pair != null)
keySet.add(pair.key);
}
return keySet;
}
/* 获取所有值 */
public List<String> valueSet() {
List<String> valueSet = new ArrayList<>();
for (Entry pair : bucket) {
if (pair != null)
valueSet.add(pair.val);
}
return valueSet;
}
/* 打印哈希表 */
public void print() {
for (Entry kv: entrySet()) {
System.out.println(kv.key + " -> " + kv.val);
}
}
} }
``` ```

View File

@ -260,14 +260,6 @@ comments: true
=== "Java" === "Java"
```java title="my_heap.java" ```java title="my_heap.java"
// 使用列表而非数组,这样无需考虑扩容问题
List<Integer> maxHeap;
/* 构造函数,建立空堆 */
public MaxHeap() {
maxHeap = new ArrayList<>();
}
/* 获取左子结点索引 */ /* 获取左子结点索引 */
int left(int i) { int left(int i) {
return 2 * i + 1; return 2 * i + 1;
@ -408,7 +400,7 @@ comments: true
```java title="my_heap.java" ```java title="my_heap.java"
/* 访问堆顶元素 */ /* 访问堆顶元素 */
public int peek() { int peek() {
return maxHeap.get(0); return maxHeap.get(0);
} }
``` ```
@ -518,7 +510,7 @@ comments: true
while (true) { while (true) {
// 获取结点 i 的父结点 // 获取结点 i 的父结点
int p = parent(i); int p = parent(i);
// 若“越过根结点”或“结点无需修复”,则结束堆化 // 当“越过根结点”或“结点无需修复”时,结束堆化
if (p < 0 || maxHeap.get(i) <= maxHeap.get(p)) if (p < 0 || maxHeap.get(i) <= maxHeap.get(p))
break; break;
// 交换两结点 // 交换两结点
@ -718,7 +710,7 @@ comments: true
ma = l; ma = l;
if (r < size() && maxHeap.get(r) > maxHeap.get(ma)) if (r < size() && maxHeap.get(r) > maxHeap.get(ma))
ma = r; ma = r;
// 若“结点 i 最大”或“越过叶结点”,则结束堆化 // 若结点 i 最大或索引 l, r 越界,则无需继续堆化,跳出
if (ma == i) break; if (ma == i) break;
// 交换两结点 // 交换两结点
swap(i, ma); swap(i, ma);
@ -902,7 +894,7 @@ comments: true
```java title="my_heap.java" ```java title="my_heap.java"
/* 构造函数,根据输入列表建堆 */ /* 构造函数,根据输入列表建堆 */
public MaxHeap(List<Integer> nums) { MaxHeap(List<Integer> nums) {
// 将列表元素原封不动添加进堆 // 将列表元素原封不动添加进堆
maxHeap = new ArrayList<>(nums); maxHeap = new ArrayList<>(nums);
// 堆化除叶结点以外的其他所有结点 // 堆化除叶结点以外的其他所有结点

View File

@ -62,11 +62,9 @@ comments: true
=== "Java" === "Java"
```java title="merge_sort.java" ```java title="merge_sort.java"
/** /* 合并左子数组和右子数组 */
* 合并左子数组和右子数组 // 左子数组区间 [left, mid]
* 左子数组区间 [left, mid] // 右子数组区间 [mid + 1, right]
* 右子数组区间 [mid + 1, right]
*/
void merge(int[] nums, int left, int mid, int right) { void merge(int[] nums, int left, int mid, int right) {
// 初始化辅助数组 // 初始化辅助数组
int[] tmp = Arrays.copyOfRange(nums, left, right + 1); int[] tmp = Arrays.copyOfRange(nums, left, right + 1);
@ -94,11 +92,11 @@ comments: true
void mergeSort(int[] nums, int left, int right) { void mergeSort(int[] nums, int left, int right) {
// 终止条件 // 终止条件
if (left >= right) return; // 当子数组长度为 1 时终止递归 if (left >= right) return; // 当子数组长度为 1 时终止递归
// 递归划分 // 划分阶段
int mid = (left + right) / 2; // 计算数组中点 int mid = (left + right) / 2; // 计算中点
mergeSort(nums, left, mid); // 递归左子数组 mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组 mergeSort(nums, mid + 1, right); // 递归右子数组
// 回溯合并 // 合并阶段
merge(nums, left, mid, right); merge(nums, left, mid, right);
} }
``` ```
@ -106,11 +104,9 @@ comments: true
=== "C++" === "C++"
```cpp title="merge_sort.cpp" ```cpp title="merge_sort.cpp"
/** /* 合并左子数组和右子数组 */
* 合并左子数组和右子数组 // 左子数组区间 [left, mid]
* 左子数组区间 [left, mid] // 右子数组区间 [mid + 1, right]
* 右子数组区间 [mid + 1, right]
*/
void merge(vector<int>& nums, int left, int mid, int right) { void merge(vector<int>& nums, int left, int mid, int right) {
// 初始化辅助数组 // 初始化辅助数组
vector<int> tmp(nums.begin() + left, nums.begin() + right + 1); vector<int> tmp(nums.begin() + left, nums.begin() + right + 1);
@ -245,11 +241,9 @@ comments: true
=== "JavaScript" === "JavaScript"
```js title="merge_sort.js" ```js title="merge_sort.js"
/** /* 合并左子数组和右子数组 */
* 合并左子数组和右子数组 // 左子数组区间 [left, mid]
* 左子数组区间 [left, mid] // 右子数组区间 [mid + 1, right]
* 右子数组区间 [mid + 1, right]
*/
function merge(nums, left, mid, right) { function merge(nums, left, mid, right) {
// 初始化辅助数组 // 初始化辅助数组
let tmp = nums.slice(left, right + 1); let tmp = nums.slice(left, right + 1);
@ -290,11 +284,9 @@ comments: true
=== "TypeScript" === "TypeScript"
```typescript title="merge_sort.ts" ```typescript title="merge_sort.ts"
/** /* 合并左子数组和右子数组 */
* 合并左子数组和右子数组 // 左子数组区间 [left, mid]
* 左子数组区间 [left, mid] // 右子数组区间 [mid + 1, right]
* 右子数组区间 [mid + 1, right]
*/
function merge(nums: number[], left: number, mid: number, right: number): void { function merge(nums: number[], left: number, mid: number, right: number): void {
// 初始化辅助数组 // 初始化辅助数组
let tmp = nums.slice(left, right + 1); let tmp = nums.slice(left, right + 1);
@ -341,11 +333,9 @@ comments: true
=== "C#" === "C#"
```csharp title="merge_sort.cs" ```csharp title="merge_sort.cs"
/** /* 合并左子数组和右子数组 */
* 合并左子数组和右子数组 // 左子数组区间 [left, mid]
* 左子数组区间 [left, mid] // 右子数组区间 [mid + 1, right]
* 右子数组区间 [mid + 1, right]
*/
void merge(int[] nums, int left, int mid, int right) void merge(int[] nums, int left, int mid, int right)
{ {
// 初始化辅助数组 // 初始化辅助数组

View File

@ -45,7 +45,7 @@ comments: true
=== "Java" === "Java"
``` java title="quick_sort.java" ```java title="quick_sort.java"
/* 元素交换 */ /* 元素交换 */
void swap(int[] nums, int i, int j) { void swap(int[] nums, int i, int j) {
int tmp = nums[i]; int tmp = nums[i];
@ -476,7 +476,16 @@ comments: true
// 将中位数交换至数组最左端 // 将中位数交换至数组最左端
swap(nums, left, med); swap(nums, left, med);
// 以 nums[left] 作为基准数 // 以 nums[left] 作为基准数
// 下同省略... int i = left, j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left])
j--; // 从右向左找首个小于基准数的元素
while (i < j && nums[i] <= nums[left])
i++; // 从左向右找首个大于基准数的元素
swap(nums, i, j); // 交换这两个元素
}
swap(nums, i, left); // 将基准数交换至两子数组的分界线
return i; // 返回基准数的索引
} }
``` ```

View File

@ -433,6 +433,21 @@ comments: true
public Integer peekLast() { public Integer peekLast() {
return isEmpty() ? null : rear.val; return isEmpty() ? null : rear.val;
} }
/* 打印双向队列 */
public void print() {
if (isEmpty()) {
System.out.println("[ ]");
return;
}
List<String> list = new ArrayList<>();
ListNode head = front;
while (head != null) {
list.add(String.valueOf(head.val));
head = head.next;
}
System.out.println("[" + String.join(", ", list) + "]");
}
} }
``` ```

View File

@ -293,14 +293,17 @@ comments: true
front = null; front = null;
rear = null; rear = null;
} }
/* 获取队列的长度 */ /* 获取队列的长度 */
public int size() { public int size() {
return queSize; return queSize;
} }
/* 判断队列是否为空 */ /* 判断队列是否为空 */
public boolean isEmpty() { public boolean isEmpty() {
return size() == 0; return size() == 0;
} }
/* 入队 */ /* 入队 */
public void push(int num) { public void push(int num) {
// 尾结点后添加 num // 尾结点后添加 num
@ -316,6 +319,7 @@ comments: true
} }
queSize++; queSize++;
} }
/* 出队 */ /* 出队 */
public int poll() { public int poll() {
int num = peek(); int num = peek();
@ -324,12 +328,24 @@ comments: true
queSize--; queSize--;
return num; return num;
} }
/* 访问队首元素 */ /* 访问队首元素 */
public int peek() { public int peek() {
if (size() == 0) if (size() == 0)
throw new EmptyStackException(); throw new EmptyStackException();
return front.val; return front.val;
} }
/* 将链表转化为 Array 并返回 */
public int[] toArray() {
ListNode node = front;
int[] res = new int[size()];
for (int i = 0; i < res.length; i++) {
res[i] = node.val;
node = node.next;
}
return res;
}
} }
``` ```
@ -815,6 +831,16 @@ comments: true
throw new EmptyStackException(); throw new EmptyStackException();
return nums[front]; return nums[front];
} }
/* 返回数组 */
public int[] toArray() {
// 仅转换有效长度范围内的列表元素
int[] res = new int[queSize];
for (int i = 0, j = front; i < queSize; i++, j++) {
res[i] = nums[j % capacity()];
}
return res;
}
} }
``` ```

View File

@ -291,17 +291,21 @@ comments: true
class LinkedListStack { class LinkedListStack {
private ListNode stackPeek; // 将头结点作为栈顶 private ListNode stackPeek; // 将头结点作为栈顶
private int stkSize = 0; // 栈的长度 private int stkSize = 0; // 栈的长度
public LinkedListStack() { public LinkedListStack() {
stackPeek = null; stackPeek = null;
} }
/* 获取栈的长度 */ /* 获取栈的长度 */
public int size() { public int size() {
return stkSize; return stkSize;
} }
/* 判断栈是否为空 */ /* 判断栈是否为空 */
public boolean isEmpty() { public boolean isEmpty() {
return size() == 0; return size() == 0;
} }
/* 入栈 */ /* 入栈 */
public void push(int num) { public void push(int num) {
ListNode node = new ListNode(num); ListNode node = new ListNode(num);
@ -309,6 +313,7 @@ comments: true
stackPeek = node; stackPeek = node;
stkSize++; stkSize++;
} }
/* 出栈 */ /* 出栈 */
public int pop() { public int pop() {
int num = peek(); int num = peek();
@ -316,12 +321,24 @@ comments: true
stkSize--; stkSize--;
return num; return num;
} }
/* 访问栈顶元素 */ /* 访问栈顶元素 */
public int peek() { public int peek() {
if (size() == 0) if (size() == 0)
throw new EmptyStackException(); throw new EmptyStackException();
return stackPeek.val; return stackPeek.val;
} }
/* 将 List 转化为 Array 并返回 */
public int[] toArray() {
ListNode node = stackPeek;
int[] res = new int[size()];
for (int i = res.length - 1; i >= 0; i--) {
res[i] = node.val;
node = node.next;
}
return res;
}
} }
``` ```
@ -730,30 +747,40 @@ comments: true
// 初始化列表(动态数组) // 初始化列表(动态数组)
stack = new ArrayList<>(); stack = new ArrayList<>();
} }
/* 获取栈的长度 */ /* 获取栈的长度 */
public int size() { public int size() {
return stack.size(); return stack.size();
} }
/* 判断栈是否为空 */ /* 判断栈是否为空 */
public boolean isEmpty() { public boolean isEmpty() {
return size() == 0; return size() == 0;
} }
/* 入栈 */ /* 入栈 */
public void push(int num) { public void push(int num) {
stack.add(num); stack.add(num);
} }
/* 出栈 */ /* 出栈 */
public int pop() { public int pop() {
if (isEmpty()) if (isEmpty())
throw new EmptyStackException(); throw new EmptyStackException();
return stack.remove(size() - 1); return stack.remove(size() - 1);
} }
/* 访问栈顶元素 */ /* 访问栈顶元素 */
public int peek() { public int peek() {
if (isEmpty()) if (isEmpty())
throw new EmptyStackException(); throw new EmptyStackException();
return stack.get(size() - 1); return stack.get(size() - 1);
} }
/* 将 List 转化为 Array 并返回 */
public Object[] toArray() {
return stack.toArray();
}
} }
``` ```

View File

@ -28,7 +28,7 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "Java" === "Java"
```java title="avl_tree.java" ```java title=""
/* AVL 树结点类 */ /* AVL 树结点类 */
class TreeNode { class TreeNode {
public int val; // 结点值 public int val; // 结点值
@ -41,7 +41,7 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "C++" === "C++"
```cpp title="avl_tree.cpp" ```cpp title=""
/* AVL 树结点类 */ /* AVL 树结点类 */
struct TreeNode { struct TreeNode {
int val{}; // 结点值 int val{}; // 结点值
@ -55,7 +55,7 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "Python" === "Python"
```python title="avl_tree.py" ```python title=""
""" AVL 树结点类 """ """ AVL 树结点类 """
class TreeNode: class TreeNode:
def __init__(self, val=None, left=None, right=None): def __init__(self, val=None, left=None, right=None):
@ -67,7 +67,7 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "Go" === "Go"
```go title="avl_tree.go" ```go title=""
/* AVL 树结点类 */ /* AVL 树结点类 */
type TreeNode struct { type TreeNode struct {
Val int // 结点值 Val int // 结点值
@ -79,36 +79,47 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "JavaScript" === "JavaScript"
```js title="avl_tree.js" ```js title=""
class TreeNode { class TreeNode {
val; // 结点值 val; // 结点值
height; //结点高度
left; // 左子结点指针 left; // 左子结点指针
right; // 右子结点指针 right; // 右子结点指针
height; //结点高度
constructor(val, left, right, height) { constructor(val, left, right, height) {
this.val = val === undefined ? 0 : val; this.val = val === undefined ? 0 : val;
this.height = height === undefined ? 0 : height;
this.left = left === undefined ? null : left; this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right; this.right = right === undefined ? null : right;
this.height = height === undefined ? 0 : height;
} }
} }
``` ```
=== "TypeScript" === "TypeScript"
```typescript title="avl_tree.ts" ```typescript title=""
class TreeNode {
val: number; // 结点值
height: number; // 结点高度
left: TreeNode | null; // 左子结点指针
right: TreeNode | null; // 右子结点指针
constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.height = height === undefined ? 0 : height;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
``` ```
=== "C" === "C"
```c title="avl_tree.c" ```c title=""
``` ```
=== "C#" === "C#"
```csharp title="avl_tree.cs" ```csharp title=""
/* AVL 树结点类 */ /* AVL 树结点类 */
class TreeNode { class TreeNode {
public int val; // 结点值 public int val; // 结点值
@ -121,7 +132,7 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "Swift" === "Swift"
```swift title="avl_tree.swift" ```swift title=""
/* AVL 树结点类 */ /* AVL 树结点类 */
class TreeNode { class TreeNode {
var val: Int // 结点值 var val: Int // 结点值
@ -138,7 +149,7 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "Zig" === "Zig"
```zig title="avl_tree.zig" ```zig title=""
``` ```
@ -236,7 +247,17 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "TypeScript" === "TypeScript"
```typescript title="avl_tree.ts" ```typescript title="avl_tree.ts"
/* 获取结点高度 */
height(node: TreeNode): number {
// 空结点高度为 -1 ,叶结点高度为 0
return node === null ? -1 : node.height;
}
/* 更新结点高度 */
updateHeight(node: TreeNode): void {
// 结点高度等于最高子树高度 + 1
node.height = Math.max(this.height(node.left), this.height(node.right)) + 1;
}
``` ```
=== "C" === "C"
@ -292,8 +313,8 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "Java" === "Java"
```java title="avl_tree.java" ```java title="avl_tree.java"
/* 获取结点平衡因子 */ /* 获取平衡因子 */
public int balanceFactor(TreeNode node) { int balanceFactor(TreeNode node) {
// 空结点平衡因子为 0 // 空结点平衡因子为 0
if (node == null) return 0; if (node == null) return 0;
// 结点平衡因子 = 左子树高度 - 右子树高度 // 结点平衡因子 = 左子树高度 - 右子树高度
@ -354,7 +375,13 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "TypeScript" === "TypeScript"
```typescript title="avl_tree.ts" ```typescript title="avl_tree.ts"
/* 获取平衡因子 */
balanceFactor(node: TreeNode): number {
// 空结点平衡因子为 0
if (node === null) return 0;
// 结点平衡因子 = 左子树高度 - 右子树高度
return this.height(node.left) - this.height(node.right);
}
``` ```
=== "C" === "C"
@ -408,7 +435,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
### Case 1 - 右旋 ### Case 1 - 右旋
如下图所示(结点下方为「平衡因子」),从底至顶看,二叉树中首个失衡结点是 **结点 3**。我们聚焦在以该失衡结点为根结点的子树上,将该结点记为 `node` ,将其左子点记为 `child` ,执行「右旋」操作。完成右旋后,该子树已经恢复平衡,并且仍然为二叉搜索树。 如下图所示(结点下方为「平衡因子」),从底至顶看,二叉树中首个失衡结点是 **结点 3**。我们聚焦在以该失衡结点为根结点的子树上,将该结点记为 `node` ,将其左子点记为 `child` ,执行「右旋」操作。完成右旋后,该子树已经恢复平衡,并且仍然为二叉搜索树。
=== "Step 1" === "Step 1"
![right_rotate_step1](avl_tree.assets/right_rotate_step1.png) ![right_rotate_step1](avl_tree.assets/right_rotate_step1.png)
@ -441,7 +468,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
// 更新结点高度 // 更新结点高度
updateHeight(node); updateHeight(node);
updateHeight(child); updateHeight(child);
// 返回旋转后子树的根 // 返回旋转后子树的根
return child; return child;
} }
``` ```
@ -459,7 +486,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
// 更新结点高度 // 更新结点高度
updateHeight(node); updateHeight(node);
updateHeight(child); updateHeight(child);
// 返回旋转后子树的根 // 返回旋转后子树的根
return child; return child;
} }
``` ```
@ -477,7 +504,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
# 更新结点高度 # 更新结点高度
self.__update_height(node) self.__update_height(node)
self.__update_height(child) self.__update_height(child)
# 返回旋转后子树的根 # 返回旋转后子树的根
return child return child
``` ```
@ -494,7 +521,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
// 更新结点高度 // 更新结点高度
updateHeight(node) updateHeight(node)
updateHeight(child) updateHeight(child)
// 返回旋转后子树的根 // 返回旋转后子树的根
return child return child
} }
``` ```
@ -504,15 +531,15 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
```js title="avl_tree.js" ```js title="avl_tree.js"
/* 右旋操作 */ /* 右旋操作 */
rightRotate(node) { rightRotate(node) {
let child = node.left; const child = node.left;
let 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;
} }
``` ```
@ -520,7 +547,19 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
=== "TypeScript" === "TypeScript"
```typescript title="avl_tree.ts" ```typescript title="avl_tree.ts"
/* 右旋操作 */
rightRotate(node: TreeNode): TreeNode {
const child = node.left;
const grandChild = child.right;
// 以 child 为原点,将 node 向右旋转
child.right = node;
node.left = grandChild;
// 更新结点高度
this.updateHeight(node);
this.updateHeight(child);
// 返回旋转后子树的根结点
return child;
}
``` ```
=== "C" === "C"
@ -543,7 +582,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
// 更新结点高度 // 更新结点高度
updateHeight(node); updateHeight(node);
updateHeight(child); updateHeight(child);
// 返回旋转后子树的根 // 返回旋转后子树的根
return child; return child;
} }
``` ```
@ -561,7 +600,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
// 更新结点高度 // 更新结点高度
updateHeight(node: node) updateHeight(node: node)
updateHeight(node: child) updateHeight(node: child)
// 返回旋转后子树的根 // 返回旋转后子树的根
return child return child
} }
``` ```
@ -588,7 +627,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
```java title="avl_tree.java" ```java title="avl_tree.java"
/* 左旋操作 */ /* 左旋操作 */
private TreeNode leftRotate(TreeNode node) { TreeNode leftRotate(TreeNode node) {
TreeNode child = node.right; TreeNode child = node.right;
TreeNode grandChild = child.left; TreeNode grandChild = child.left;
// 以 child 为原点,将 node 向左旋转 // 以 child 为原点,将 node 向左旋转
@ -597,7 +636,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
// 更新结点高度 // 更新结点高度
updateHeight(node); updateHeight(node);
updateHeight(child); updateHeight(child);
// 返回旋转后子树的根 // 返回旋转后子树的根
return child; return child;
} }
``` ```
@ -615,7 +654,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
// 更新结点高度 // 更新结点高度
updateHeight(node); updateHeight(node);
updateHeight(child); updateHeight(child);
// 返回旋转后子树的根 // 返回旋转后子树的根
return child; return child;
} }
``` ```
@ -633,7 +672,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
# 更新结点高度 # 更新结点高度
self.__update_height(node) self.__update_height(node)
self.__update_height(child) self.__update_height(child)
# 返回旋转后子树的根 # 返回旋转后子树的根
return child return child
``` ```
@ -650,7 +689,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
// 更新结点高度 // 更新结点高度
updateHeight(node) updateHeight(node)
updateHeight(child) updateHeight(child)
// 返回旋转后子树的根 // 返回旋转后子树的根
return child return child
} }
``` ```
@ -660,15 +699,15 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
```js title="avl_tree.js" ```js title="avl_tree.js"
/* 左旋操作 */ /* 左旋操作 */
leftRotate(node) { leftRotate(node) {
let child = node.right; const child = node.right;
let 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;
} }
``` ```
@ -676,7 +715,19 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
=== "TypeScript" === "TypeScript"
```typescript title="avl_tree.ts" ```typescript title="avl_tree.ts"
/* 左旋操作 */
leftRotate(node: TreeNode): TreeNode {
const child = node.right;
const grandChild = child.left;
// 以 child 为原点,将 node 向左旋转
child.left = node;
node.right = grandChild;
// 更新结点高度
this.updateHeight(node);
this.updateHeight(child);
// 返回旋转后子树的根结点
return child;
}
``` ```
=== "C" === "C"
@ -701,7 +752,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
// 更新结点高度 // 更新结点高度
updateHeight(node); updateHeight(node);
updateHeight(child); updateHeight(child);
// 返回旋转后子树的根 // 返回旋转后子树的根
return child; return child;
} }
``` ```
@ -719,7 +770,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
// 更新结点高度 // 更新结点高度
updateHeight(node: node) updateHeight(node: node)
updateHeight(node: child) updateHeight(node: child)
// 返回旋转后子树的根 // 返回旋转后子树的根
return child return child
} }
@ -902,7 +953,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
/* 执行旋转操作,使该子树重新恢复平衡 */ /* 执行旋转操作,使该子树重新恢复平衡 */
rotate(node) { rotate(node) {
// 获取结点 node 的平衡因子 // 获取结点 node 的平衡因子
let 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) {
@ -933,7 +984,35 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
=== "TypeScript" === "TypeScript"
```typescript title="avl_tree.ts" ```typescript title="avl_tree.ts"
/* 执行旋转操作,使该子树重新恢复平衡 */
rotate(node: TreeNode): TreeNode {
// 获取结点 node 的平衡因子
const balanceFactor = this.balanceFactor(node);
// 左偏树
if (balanceFactor > 1) {
if (this.balanceFactor(node.left) >= 0) {
// 右旋
return this.rightRotate(node);
} else {
// 先左旋后右旋
node.left = this.leftRotate(node.left);
return this.rightRotate(node);
}
}
// 右偏树
if (balanceFactor < -1) {
if (this.balanceFactor(node.right) <= 0) {
// 左旋
return this.leftRotate(node);
} else {
// 先右旋后左旋
node.right = this.rightRotate(node.right);
return this.leftRotate(node);
}
}
// 平衡树,无需旋转,直接返回
return node;
}
``` ```
=== "C" === "C"
@ -1053,7 +1132,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
updateHeight(node); // 更新结点高度 updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node); node = rotate(node);
// 返回子树的根 // 返回子树的根
return node; return node;
} }
``` ```
@ -1080,7 +1159,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
updateHeight(node); // 更新结点高度 updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node); node = rotate(node);
// 返回子树的根 // 返回子树的根
return node; return node;
} }
``` ```
@ -1137,7 +1216,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
updateHeight(node) updateHeight(node)
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node) node = rotate(node)
// 返回子树的根 // 返回子树的根
return node return node
} }
``` ```
@ -1161,7 +1240,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
this.updateHeight(node); // 更新结点高度 this.updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = this.rotate(node); node = this.rotate(node);
// 返回子树的根 // 返回子树的根
return node; return node;
} }
``` ```
@ -1169,7 +1248,29 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
=== "TypeScript" === "TypeScript"
```typescript title="avl_tree.ts" ```typescript title="avl_tree.ts"
/* 插入结点 */
insert(val: number): TreeNode {
this.root = this.insertHelper(this.root, val);
return this.root;
}
/* 递归插入结点(辅助函数) */
insertHelper(node: TreeNode, val: number): TreeNode {
if (node === null) return new TreeNode(val);
/* 1. 查找插入位置,并插入结点 */
if (val < node.val) {
node.left = this.insertHelper(node.left, val);
} else if (val > node.val) {
node.right = this.insertHelper(node.right, val);
} else {
return node; // 重复结点不插入,直接返回
}
this.updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = this.rotate(node);
// 返回子树的根结点
return node;
}
``` ```
=== "C" === "C"
@ -1204,7 +1305,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
updateHeight(node); // 更新结点高度 updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node); node = rotate(node);
// 返回子树的根 // 返回子树的根
return node; return node;
} }
``` ```
@ -1236,7 +1337,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
updateHeight(node: node) // 更新结点高度 updateHeight(node: node) // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node: node) node = rotate(node: node)
// 返回子树的根 // 返回子树的根
return node return node
} }
``` ```
@ -1287,7 +1388,17 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
updateHeight(node); // 更新结点高度 updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node); node = rotate(node);
// 返回子树的根节点 // 返回子树的根结点
return node;
}
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
TreeNode getInOrderNext(TreeNode node) {
if (node == null) return node;
// 循环访问左子结点,直到叶结点时为最小结点,跳出
while (node.left != null) {
node = node.left;
}
return node; return node;
} }
``` ```
@ -1332,7 +1443,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
updateHeight(node); // 更新结点高度 updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node); node = rotate(node);
// 返回子树的根 // 返回子树的根
return node; return node;
} }
``` ```
@ -1416,7 +1527,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
updateHeight(node) updateHeight(node)
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node) node = rotate(node)
// 返回子树的根 // 返回子树的根
return node return node
} }
``` ```
@ -1438,14 +1549,14 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
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) {
let child = node.left !== null ? node.left : node.right; const child = node.left !== null ? node.left : node.right;
// 子结点数量 = 0 ,直接删除 node 并返回 // 子结点数量 = 0 ,直接删除 node 并返回
if (child === null) return null; if (child === null) return null;
// 子结点数量 = 1 ,直接删除 node // 子结点数量 = 1 ,直接删除 node
else node = child; else node = child;
} else { } else {
// 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点 // 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点
let 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;
} }
@ -1453,7 +1564,27 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
this.updateHeight(node); // 更新结点高度 this.updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = this.rotate(node); node = this.rotate(node);
// 返回子树的根节点 // 返回子树的根结点
return node;
}
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
getInOrderNext(node) {
if (node === null) return node;
// 循环访问左子结点,直到叶结点时为最小结点,跳出
while (node.left !== null) {
node = node.left;
}
return node;
}
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
getInOrderNext(node) {
if (node === null) return node;
// 循环访问左子结点,直到叶结点时为最小结点,跳出
while (node.left !== null) {
node = node.left;
}
return node; return node;
} }
``` ```
@ -1461,7 +1592,53 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
=== "TypeScript" === "TypeScript"
```typescript title="avl_tree.ts" ```typescript title="avl_tree.ts"
/* 删除结点 */
remove(val: number): TreeNode {
this.root = this.removeHelper(this.root, val);
return this.root;
}
/* 递归删除结点(辅助函数) */
removeHelper(node: TreeNode, val: number): TreeNode {
if (node === null) return null;
/* 1. 查找结点,并删除之 */
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 (node.left === null || node.right === null) {
const child = node.left !== null ? node.left : node.right;
// 子结点数量 = 0 ,直接删除 node 并返回
if (child === null) {
return null;
} else {
// 子结点数量 = 1 ,直接删除 node
node = child;
}
} else {
// 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点
const temp = this.getInOrderNext(node.right);
node.right = this.removeHelper(node.right, temp.val);
node.val = temp.val;
}
}
this.updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = this.rotate(node);
// 返回子树的根结点
return node;
}
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
getInOrderNext(node: TreeNode): TreeNode {
if (node === null) return node;
// 循环访问左子结点,直到叶结点时为最小结点,跳出
while (node.left !== null) {
node = node.left;
}
return node;
}
``` ```
=== "C" === "C"
@ -1512,7 +1689,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
updateHeight(node); // 更新结点高度 updateHeight(node); // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node); node = rotate(node);
// 返回子树的根 // 返回子树的根
return node; return node;
} }
``` ```
@ -1559,7 +1736,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
updateHeight(node: node) // 更新结点高度 updateHeight(node: node) // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */ /* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node: node) node = rotate(node: node)
// 返回子树的根 // 返回子树的根
return node return node
} }
``` ```

View File

@ -556,8 +556,6 @@ comments: true
// 删除结点 cur // 删除结点 cur
if (pre.left == cur) pre.left = child; if (pre.left == cur) pre.left = child;
else pre.right = child; else pre.right = child;
// 释放内存
delete cur;
} }
// 子结点数量 = 2 // 子结点数量 = 2
else { else {
@ -573,7 +571,7 @@ comments: true
} }
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */ /* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
public TreeNode getInOrderNext(TreeNode root) { TreeNode getInOrderNext(TreeNode root) {
if (root == null) return root; if (root == null) return root;
// 循环访问左子结点,直到叶结点时为最小结点,跳出 // 循环访问左子结点,直到叶结点时为最小结点,跳出
while (root.left != null) { while (root.left != null) {

View File

@ -197,7 +197,7 @@ comments: true
```python title="binary_tree.py" ```python title="binary_tree.py"
""" 初始化二叉树 """ """ 初始化二叉树 """
# 初始化 # 初始化
n1 = TreeNode(val=1) n1 = TreeNode(val=1)
n2 = TreeNode(val=2) n2 = TreeNode(val=2)
n3 = TreeNode(val=3) n3 = TreeNode(val=3)
@ -343,7 +343,7 @@ comments: true
# 在 n1 -> n2 中间插入结点 P # 在 n1 -> n2 中间插入结点 P
n1.left = p n1.left = p
p.left = n2 p.left = n2
# 删除点 P # 删除点 P
n1.left = n2 n1.left = n2
``` ```

View File

@ -52,7 +52,7 @@ comments: true
while (!queue.empty()) { while (!queue.empty()) {
TreeNode* node = queue.front(); TreeNode* node = queue.front();
queue.pop(); // 队列出队 queue.pop(); // 队列出队
vec.push_back(node->val); // 保存结点 vec.push_back(node->val); // 保存结点
if (node->left != nullptr) if (node->left != nullptr)
queue.push(node->left); // 左子结点入队 queue.push(node->left); // 左子结点入队
if (node->right != nullptr) if (node->right != nullptr)
@ -74,7 +74,7 @@ comments: true
res = [] res = []
while queue: while queue:
node = queue.popleft() # 队列出队 node = queue.popleft() # 队列出队
res.append(node.val) # 保存点值 res.append(node.val) # 保存点值
if node.left is not None: if node.left is not None:
queue.append(node.left) # 左子结点入队 queue.append(node.left) # 左子结点入队
if node.right is not None: if node.right is not None:
@ -95,7 +95,7 @@ comments: true
for queue.Len() > 0 { for queue.Len() > 0 {
// poll // poll
node := queue.Remove(queue.Front()).(*TreeNode) node := queue.Remove(queue.Front()).(*TreeNode)
// 保存结点 // 保存结点
nums = append(nums, node.Val) nums = append(nums, node.Val)
if node.Left != nil { if node.Left != nil {
// 左子结点入队 // 左子结点入队
@ -121,7 +121,7 @@ comments: true
let list = []; let list = [];
while (queue.length) { while (queue.length) {
let node = queue.shift(); // 队列出队 let node = queue.shift(); // 队列出队
list.push(node.val); // 保存结点 list.push(node.val); // 保存结点
if (node.left) if (node.left)
queue.push(node.left); // 左子结点入队 queue.push(node.left); // 左子结点入队
if (node.right) if (node.right)
@ -142,7 +142,7 @@ comments: true
const list: number[] = []; const list: number[] = [];
while (queue.length) { while (queue.length) {
let node = queue.shift() as TreeNode; // 队列出队 let node = queue.shift() as TreeNode; // 队列出队
list.push(node.val); // 保存结点 list.push(node.val); // 保存结点
if (node.left) { if (node.left) {
queue.push(node.left); // 左子结点入队 queue.push(node.left); // 左子结点入队
} }
@ -196,7 +196,7 @@ comments: true
var list: [Int] = [] var list: [Int] = []
while !queue.isEmpty { while !queue.isEmpty {
let node = queue.removeFirst() // 队列出队 let node = queue.removeFirst() // 队列出队
list.append(node.val) // 保存结点 list.append(node.val) // 保存结点
if let left = node.left { if let left = node.left {
queue.append(left) // 左子结点入队 queue.append(left) // 左子结点入队
} }

View File

@ -68,3 +68,9 @@ body {
--md-text-font-family: -apple-system,BlinkMacSystemFont,var(--md-text-font,_),Helvetica,Arial,sans-serif; --md-text-font-family: -apple-system,BlinkMacSystemFont,var(--md-text-font,_),Helvetica,Arial,sans-serif;
--md-code-font-family: var(--md-code-font,_),SFMono-Regular,Consolas,Menlo,-apple-system,BlinkMacSystemFont,var(--md-text-font,_),monospace; --md-code-font-family: var(--md-code-font,_),SFMono-Regular,Consolas,Menlo,-apple-system,BlinkMacSystemFont,var(--md-text-font,_),monospace;
} }
/* max height of code block */
/* https://github.com/squidfunk/mkdocs-material/issues/3444 */
.md-typeset pre > code {
max-height: 30rem;
}