Merge branch 'master' of github.com:krahets/hello-algo

pull/306/head
Yudong Jin 2 years ago
commit c25b1d98d5

@ -1,6 +1,6 @@
/**
* File: linked_list.c
* Created Time: 2022-01-12
* Created Time: 2023-01-12
* Author: Zero (glj0@outlook.com)
*/

@ -1,62 +1,64 @@
/**
* File: list.c
* Created Time: 2022-01-12
* File: my_list.c
* Created Time: 2023-01-12
* Author: Zero (glj0@outlook.com)
*/
#include "../include/include.h"
// 用数组实现 list
struct mylist {
int* nums; // 数组(存储列表元素)
struct myList {
int *nums; // 数组(存储列表元素)
int capacity; // 列表容量
int size; // 列表大小
int extendRatio; // 列表每次扩容的倍数
};
typedef struct mylist MyList;
typedef struct myList myList;
/* 前置声明 */
void extendCapacity(MyList *list);
void extendCapacity(myList *list);
/* 构造函数 */
void newMyList(MyList *list) {
myList *newMyList() {
myList *list = malloc(sizeof(myList));
list->capacity = 10;
list->nums = malloc(sizeof(int) * list->capacity);
list->size = 0;
list->extendRatio = 2;
return list;
}
/* 析构函数 */
void delMyList(MyList *list) {
list->size = 0;
void delMyList(myList *list) {
free(list->nums);
free(list);
}
/* 获取列表长度 */
int size(MyList *list) {
int size(myList *list) {
return list->size;
}
/* 获取列表容量 */
int capacity(MyList *list) {
int capacity(myList *list) {
return list->capacity;
}
/* 访问元素 */
int get(MyList *list, int index) {
int get(myList *list, int index) {
assert(index < list->size);
return list->nums[index];
}
/* 更新元素 */
void set(MyList *list, int index, int num) {
void set(myList *list, int index, int num) {
assert(index < list->size);
list->nums[index] = num;
}
/* 尾部添加元素 */
void add(MyList *list, int num) {
void add(myList *list, int num) {
if (size(list) == capacity(list)) {
extendCapacity(list); // 扩容
}
@ -65,10 +67,10 @@ void add(MyList *list, int num) {
}
/* 中间插入元素 */
void insert(MyList *list, int index, int num) {
void insert(myList *list, int index, int num) {
assert(index < size(list));
for (int i = size(list); i > index; --i) {
list->nums[i] = list->nums[i-1];
list->nums[i] = list->nums[i - 1];
}
list->nums[index] = num;
list->size++;
@ -77,25 +79,25 @@ void insert(MyList *list, int index, int num) {
/* 删除元素 */
// 由于引入了 stdio.h ,此处无法使用 remove 关键词
// 详见 https://github.com/krahets/hello-algo/pull/244#discussion_r1067863888
int removeNum(MyList *list, int index) {
int removeNum(myList *list, int index) {
assert(index < size(list));
int num = list->nums[index];
for (int i = index; i < size(list) - 1; i++) {
list->nums[i] = list->nums[i+1];
list->nums[i] = list->nums[i + 1];
}
list->size--;
return num;
}
/* 列表扩容 */
void extendCapacity(MyList *list) {
void extendCapacity(myList *list) {
// 先分配空间
int newCapacity = capacity(list) * list->extendRatio;
int *extend = (int *)malloc(sizeof(int) * newCapacity);
int *extend = (int *) malloc(sizeof(int) * newCapacity);
int *temp = list->nums;
// 拷贝旧数据到新数据
for(int i = 0; i < size(list); i++)
for (int i = 0; i < size(list); i++)
extend[i] = list->nums[i];
// 释放旧数据
@ -107,53 +109,52 @@ void extendCapacity(MyList *list) {
}
/* 将列表转换为 Array 用于打印 */
int* toArray(MyList *list) {
int *toArray(myList *list) {
return list->nums;
}
int main() {
/* 初始化列表 */
MyList list;
newMyList(&list);
myList *list = newMyList();
/* 尾部添加元素 */
add(&list, 1);
add(&list, 3);
add(&list, 2);
add(&list, 5);
add(&list, 4);
add(list, 1);
add(list, 3);
add(list, 2);
add(list, 5);
add(list, 4);
printf("列表 list = ");
printArray(toArray(&list), size(&list));
printf("容量 = %d ,长度 = %d\r\n", capacity(&list), size(&list));
printArray(toArray(list), size(list));
printf("容量 = %d ,长度 = %d\n", capacity(list), size(list));
/* 中间插入元素 */
insert(&list, 3, 6);
insert(list, 3, 6);
printf("在索引 3 处插入数字 6 ,得到 list = ");
printArray(toArray(&list), size(&list));
printArray(toArray(list), size(list));
/* 删除元素 */
removeNum(&list, 3);
removeNum(list, 3);
printf("删除索引 3 处的元素,得到 list = ");
printArray(toArray(&list), size(&list));
printArray(toArray(list), size(list));
/* 访问元素 */
int num = get(&list, 1);
printf("访问索引 1 处的元素,得到 num = %d\r\n", num);
int num = get(list, 1);
printf("访问索引 1 处的元素,得到 num = %d\n", num);
/* 更新元素 */
set(&list, 1, 0);
set(list, 1, 0);
printf("将索引 1 处的元素更新为 0 ,得到 list = ");
printArray(toArray(&list), size(&list));
printArray(toArray(list), size(list));
/* 测试扩容机制 */
for (int i = 0; i < 10; i++) {
// 在 i = 5 时,列表长度将超出列表容量,此时触发扩容机制
add(&list, i);
add(list, i);
}
printf("扩容后的列表 list = ");
printArray(toArray(&list), size(&list));
printf("容量 = %d ,长度 = %d\r\n", capacity(&list), size(&list));
printArray(toArray(list), size(list));
printf("容量 = %d ,长度 = %d\n", capacity(list), size(list));
/* 析构函数,释放分配内存 */
delMyList(&list);
/* 释放分配内存 */
delMyList(list);
}

@ -1,2 +1,3 @@
add_executable(time_complexity time_complexity.c )
add_executable(worst_best_time_complexity worst_best_time_complexity.c)
add_executable(worst_best_time_complexity worst_best_time_complexity.c)
add_executable(leetcode_two_sum leetcode_two_sum.c)

@ -0,0 +1,85 @@
/**
* File: leetcode_two_sum.c
* Created Time: 2023-01-19
* Author: Reanon (793584285@qq.com)
*/
#include "../include/include.h"
/* 暴力解法 */
int *twoSumBruteForce(int *nums, int numsSize, int target, int *returnSize) {
for (int i = 0; i < numsSize; ++i) {
for (int j = i + 1; j < numsSize; ++j) {
if (nums[i] + nums[j] == target) {
int *ret = malloc(sizeof(int) * 2);
ret[0] = i, ret[1] = j;
*returnSize = 2;
return ret;
}
}
}
*returnSize = 0;
return NULL;
}
/* 哈希表 */
struct hashTable {
int key;
int val;
// 借助 LetCode 上常用的哈希表
UT_hash_handle hh;
};
typedef struct hashTable hashTable;
hashTable *find(hashTable *h, int key) {
hashTable *tmp;
HASH_FIND_INT(h, &key, tmp);
return tmp;
}
void insert(hashTable *h, int key, int val) {
hashTable *t = find(h, key);
if (t == NULL) {
hashTable *tmp = malloc(sizeof(hashTable));
tmp->key = key, tmp->val = val;
HASH_ADD_INT(h, key, tmp);
} else {
t->val = val;
}
}
int *twoSumHashTable(int *nums, int numsSize, int target, int *returnSize) {
hashTable *hashtable = NULL;
for (int i = 0; i < numsSize; i++) {
hashTable *t = find(hashtable, target - nums[i]);
if (t != NULL) {
int *ret = malloc(sizeof(int) * 2);
ret[0] = t->val, ret[1] = i;
*returnSize = 2;
return ret;
}
insert(hashtable, nums[i], i);
}
*returnSize = 0;
return NULL;
}
int main() {
// ======= Test Case =======
int nums[] = {2, 7, 11, 15};
int target = 9;
// ====== Driver Code ======
int returnSize;
int *res = twoSumBruteForce(nums, sizeof(nums) / sizeof(int), target, &returnSize);
// 方法一
printf("方法一 res = ");
printArray(res, returnSize);
// 方法二
res = twoSumHashTable(nums, sizeof(nums) / sizeof(int), target, &returnSize);
printf("方法二 res = ");
printArray(res, returnSize);
return 0;
}

@ -63,7 +63,7 @@ int medianThree(int nums[], int left, int mid, int right) {
}
// 哨兵划分(三数取中值)
int QuickSortMedianPartition(int nums[], int left, int right) {
int quickSortMedianPartition(int nums[], int left, int right) {
// 选取三个候选元素的中位数
int med = medianThree(nums, left, (left + right) / 2, right);
// 将中位数交换至数组最左端
@ -87,7 +87,7 @@ void quickSortMedian(int nums[], int left, int right) {
if (left >= right)
return;
// 哨兵划分
int pivot = QuickSortMedianPartition(nums, left, right);
int pivot = quickSortMedianPartition(nums, left, right);
// 递归左子数组、右子数组
quickSortMedian(nums, left, pivot - 1);
quickSortMedian(nums, pivot + 1, right);

@ -1,123 +1,103 @@
/**
* File: array_stack.c
* Created Time: 2022-01-12
* Created Time: 2023-01-12
* Author: Zero (glj0@outlook.com)
*/
#include "../include/include.h"
#define MAX_SIZE 5000
/* 基于数组实现的栈 */
struct ArrayStack {
int *stackTop;
struct arrayStack {
int *data;
int size;
int capacity;
};
typedef struct ArrayStack ArrayStack;
typedef struct arrayStack arrayStack;
/* 内部调用 */
/* 获取栈容量 */
static int capacity(ArrayStack *stk) {
return stk->capacity;
}
/* 栈自动扩容 */
static void extendCapacity(ArrayStack *stk) {
// 先分配空间
int newCapacity = capacity(stk) * 2;
int *extend = (int *)malloc(sizeof(int) * newCapacity);
int *temp = stk->stackTop;
// 拷贝旧数据到新数据
for(int i=0; i<stk->size; i++)
extend[i] = temp[i];
// 释放旧数据
free(temp);
// 更新新数据
stk->stackTop = extend;
stk->capacity = newCapacity;
}
/* 构造函数 */
void newArrayStack(ArrayStack *stk) {
stk->capacity = 10;
stk->size = 0;
stk->stackTop = (int *)malloc(sizeof(int) * stk->capacity);
}
/* 析构函数 */
void delArrayStack(ArrayStack *stk) {
stk->capacity = 0;
stk->size = 0;
free(stk->stackTop);
arrayStack *newArrayStack() {
arrayStack *s = malloc(sizeof(arrayStack));
// 初始化一个大容量,避免扩容
s->data = malloc(sizeof(int) * MAX_SIZE);
s->size = 0;
return s;
}
/* 获取栈的长度 */
int size(ArrayStack *stk) {
return stk->size;
int size(arrayStack *s) {
return s->size;
}
/* 判断栈是否为空 */
bool empty(ArrayStack *stk) {
return size(stk) == 0;
}
/* 访问栈顶元素 */
int top(ArrayStack *stk) {
return stk->stackTop[size(stk) - 1];
bool isEmpty(arrayStack *s) {
return s->size == 0;
}
/* 入栈 */
void push(ArrayStack *stk, int num) {
if (size(stk) == capacity(stk))
extendCapacity(stk); // 需要扩容
void push(arrayStack *s, int num) {
if (s->size == MAX_SIZE) {
printf("stack is full.\n");
return;
}
s->data[s->size] = num;
s->size++;
}
stk->stackTop[size(stk)] = num;
stk->size++;
/* 访问栈顶元素 */
int peek(arrayStack *s) {
if (s->size == 0) {
printf("stack is empty.\n");
return NIL;
}
return s->data[s->size - 1];
}
/* 出栈 */
void pop(ArrayStack *stk) {
int num = stk->stackTop[size(stk) - 1];
stk->size--;
int pop(arrayStack *s) {
if (s->size == 0) {
printf("stack is empty.\n");
return NIL;
}
int val = peek(s);
s->size--;
return val;
}
/* Driver Code */
int main() {
/* 初始化栈 */
ArrayStack stack;
newArrayStack(&stack);
arrayStack * stack = newArrayStack();
/* 元素入栈 */
push(&stack, 1);
push(&stack, 3);
push(&stack, 2);
push(&stack, 5);
push(&stack, 4);
push(stack, 1);
push(stack, 3);
push(stack, 2);
push(stack, 5);
push(stack, 4);
printf("栈 stack = ");
printArray(stack.stackTop, size(&stack));
printArray(stack->data, stack->size);
/* 访问栈顶元素 */
int stackTop = top(&stack);
printf("栈顶元素 top = %d\r\n", stackTop);
int val = peek(stack);
printf("栈顶元素 top = %d\n", val);
/* 元素出栈 */
pop(&stack);
printf("出栈元素 pop = %d, 出栈后 stack = ", stackTop);
printArray(stack.stackTop, size(&stack));
val = pop(stack);
printf("出栈元素 pop = %d,出栈后 stack = ", val);
printArray(stack->data, stack->size);
/* 获取栈的长度 */
int stackSize = size(&stack);
printf("栈的长度 size = %d\r\n", stackSize);
int size = stack->size;
printf("栈的长度 size = %d\n", size);
/* 判断是否为空 */
bool isEmpty = empty(&stack);
printf("栈是否为空 = %s\r\n", isEmpty ? "yes" : "no");
bool empty = isEmpty(stack);
printf("栈是否为空 = %s\n", empty ? "true" : "false");
// 释放内存
free(stack->data);
free(stack);
/* 析构函数 */
delArrayStack(&stack);
return 0;
}

@ -1,110 +1,115 @@
/**
* File: linkedlist_stack.c
* Created Time: 2022-01-12
* Created Time: 2023-01-12
* Author: Zero (glj0@outlook.com)
*/
#include "../include/include.h"
/* 基于链表实现的栈 */
struct LinkedListStack {
ListNode* stackTop; // 将头结点作为栈顶
struct linkedListStack {
ListNode *top; // 将头结点作为栈顶
int size; // 栈的长度
};
typedef struct LinkedListStack LinkedListStack;
typedef struct linkedListStack linkedListStack;
/* 构造函数 */
void newLinkedListStack(LinkedListStack* stk) {
stk->stackTop = NULL;
stk->size = 0;
linkedListStack *newLinkedListStack() {
linkedListStack *s = malloc(sizeof(linkedListStack));
s->top = NULL;
s->size = 0;
return s;
}
/* 析构函数 */
void delLinkedListStack(LinkedListStack* stk) {
while(stk->stackTop) {
ListNode *n = stk->stackTop->next;
free(stk->stackTop);
stk->stackTop = n;
void delLinkedListStack(linkedListStack *s) {
while (s->top) {
ListNode *n = s->top->next;
free(s->top);
s->top = n;
}
stk->size = 0;
free(s);
}
/* 获取栈的长度 */
int size(LinkedListStack* stk) {
assert(stk);
return stk->size;
int size(linkedListStack *s) {
assert(s);
return s->size;
}
/* 判断栈是否为空 */
bool empty(LinkedListStack* stk) {
assert(stk);
return size(stk) == 0;
bool isEmpty(linkedListStack *s) {
assert(s);
return size(s) == 0;
}
/* 访问栈顶元素 */
int top(LinkedListStack* stk) {
assert(stk);
assert(size(stk) != 0);
return stk->stackTop->val;
int peek(linkedListStack *s) {
assert(s);
assert(size(s) != 0);
return s->top->val;
}
/* 入栈 */
void push(LinkedListStack* stk, int num) {
assert(stk);
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->next = stk->stackTop; // 更新新加结点指针域
node->val = num; // 更新新加结点数据域
stk->stackTop = node; // 更新栈顶
stk->size++; // 更新栈大小
void push(linkedListStack *s, int num) {
assert(s);
ListNode *node = (ListNode *) malloc(sizeof(ListNode));
node->next = s->top; // 更新新加结点指针域
node->val = num; // 更新新加结点数据域
s->top = node; // 更新栈顶
s->size++; // 更新栈大小
}
/* 出栈 */
void pop(LinkedListStack* stk) {
assert(stk);
int num = top(stk);
ListNode *tmp = stk->stackTop;
stk->stackTop = stk->stackTop->next;
int pop(linkedListStack *s) {
if (s->size == 0) {
printf("stack is empty.\n");
return NIL;
}
assert(s);
int val = peek(s);
ListNode *tmp = s->top;
s->top = s->top->next;
// 释放内存
free(tmp);
stk->size--;
s->size--;
return val;
}
/* Driver Code */
int main() {
/* 初始化栈 */
LinkedListStack stack;
/* 构造函数 */
newLinkedListStack(&stack);
// 构造函数
linkedListStack *stack = newLinkedListStack();
/* 元素入栈 */
push(&stack, 1);
push(&stack, 3);
push(&stack, 2);
push(&stack, 5);
push(&stack, 4);
push(stack, 1);
push(stack, 3);
push(stack, 2);
push(stack, 5);
push(stack, 4);
printf("栈 stack = ");
printLinkedList(stack.stackTop);
printLinkedList(stack->top);
/* 访问栈顶元素 */
int stackTop = top(&stack);
printf("栈顶元素 top = %d\r\n", stackTop);
int val = peek(stack);
printf("栈顶元素 top = %d\r\n", val);
/* 元素出栈 */
pop(&stack);
printf("出栈元素 pop = %d, 出栈后 stack = ", stackTop);
printLinkedList(stack.stackTop);
val = pop(stack);
printf("出栈元素 pop = %d, 出栈后 stack = ", val);
printLinkedList(stack->top);
/* 获取栈的长度 */
int stackSize = size(&stack);
printf("栈的长度 size = %d\r\n", stackSize);
printf("栈的长度 size = %d\n", size(stack));
/* 判断是否为空 */
bool isEmpty = empty(&stack);
printf("栈是否为空 = %s\r\n", isEmpty ? "yes" : "no");
bool empty = isEmpty(stack);
printf("栈是否为空 = %s\n", empty ? "true" : "false");
/* 析构函数 */
delLinkedListStack(&stack);
delLinkedListStack(stack);
return 0;
}

@ -1,4 +1,5 @@
add_executable(include
include_test.c
uthash.h
include.h print_util.h
list_node.h tree_node.h)

@ -14,6 +14,8 @@
#include <time.h>
#include <assert.h>
#include "uthash.h"
#include "list_node.h"
#include "tree_node.h"
#include "print_util.h"

File diff suppressed because it is too large Load Diff

@ -8,6 +8,13 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chapter_array_and_linkedlist"
version = "0.1.0"
dependencies = [
"rand",
]
[[package]]
name = "chapter_computational_complexity"
version = "0.1.0"

@ -2,4 +2,5 @@
[workspace]
members = [
"chapter_computational_complexity",
"chapter_array_and_linkedlist"
]

@ -0,0 +1,16 @@
[package]
name = "chapter_array_and_linkedlist"
version = "0.1.0"
edition = "2021"
[[bin]]
name = "array"
path = "array.rs"
[[bin]]
name = "list"
path = "list.rs"
[dependencies]
rand = "0.8.5"

@ -0,0 +1,102 @@
/**
* File: array.rs
* Created Time: 2023-01-15
* Author: xBLACICEx (xBLACKICEx@outlook.com)
*/
/* 随机返回一个数组元素 */
fn random_access(nums: &[i32]) -> i32 {
// 在区间 [0, nums.len()) 中随机抽取一个数字
let random_index = rand::random::<usize>() % nums.len();
// 获取并返回随机元素
let random_num = nums[random_index];
random_num
}
/* 扩展数组长度 */
fn extend(nums: Vec<i32>, enlarge: usize) -> Vec<i32> {
// 创建一个长度为 nums.len() + enlarge 的新 Vec
let mut res: Vec<i32> = vec![0; nums.len() + enlarge];
// 将原数组中的所有元素复制到新
for i in 0..nums.len() {
res[i] = nums[i];
}
// 返回扩展后的新数组
res
}
/* 在数组的索引 index 处插入元素 num */
fn insert(nums: &mut Vec<i32>, num: i32, index: usize) {
// 把索引 index 以及之后的所有元素向后移动一位
for i in (index + 1..nums.len()).rev() {
nums[i] = nums[i - 1];
}
// 将 num 赋给 index 处元素
nums[index] = num;
}
/* 删除索引 index 处元素 */
fn remove(nums: &mut Vec<i32>, index: usize) {
// 把索引 index 之后的所有元素向前移动一位
for i in index..nums.len() - 1 {
nums[i] = nums[i + 1];
}
}
#[allow(unused_variables)]
/* 遍历数组 */
fn traverse(nums: &[i32]) {
let mut count = 0;
// 通过索引遍历数组
for _ in 0..nums.len() {
count += 1;
}
// 直接遍历数组
for _ in nums {
count += 1;
}
}
/* 在数组中查找指定元素 */
fn find(nums: &[i32], target: i32) -> Option<usize> {
for i in 0..nums.len() {
if nums[i] == target {
return Some(i);
}
}
None
}
/* Driver Code */
fn main() {
let arr = [0; 5];
println!("数组 arr = {:?}", arr);
// 在 Rust 中,指定长度时([i32; 5])为数组
// 由于 Rust 的数组被设计为在编译期确定长度,因此只能使用常量来指定长度
// 为了方便实现扩容 extend() 方法,以下将(Vec) 看作数组Array也是rust一般情况下使用动态数组的类型
let nums = vec![1, 3, 2, 5, 4];
println!("数组 nums = {:?}", nums);
/* 随机访问 */
let random_num = random_access(&nums);
println!("在 nums 中获取随机元素 {}", random_num);
/* 长度扩展 */
let mut nums = extend(nums, 3);
println!("将数组长度扩展至 8 ,得到 nums = {:?}", nums);
/* 插入元素 */
insert(&mut nums, 6, 3);
println!("在索引 3 处插入数字 6 ,得到 nums = {:?}", nums);
/* 删除元素 */
remove(&mut nums, 2);
println!("删除索引 2 处的元素,得到 nums = {:?}", nums);
/* 遍历数组 */
traverse(&nums);
/* 查找元素 */
let index = find(&nums, 3);
println!("在 nums 中查找元素 3 ,得到索引 = {:?}", index);
}

@ -0,0 +1,67 @@
/**
* File: array.rs
* Created Time: 2023-01-18
* Author: xBLACICEx (xBLACKICEx@outlook.com)
*/
#[allow(unused_variables)]
/* Driver Code */
fn main() {
/* 初始化列表 */
let mut list: Vec<i32> = vec![1, 3, 2, 5, 4];
println!("列表 list = {:?}", list);
/* 访问元素 */
let num = list[1];
println!("访问索引 1 处的元素,得到 num = {num}");
/* 更新元素 */
list[1] = 0;
println!("将索引 1 处的元素更新为 0 ,得到 list = {:?}", list);
/* 清空列表 */
list.clear();
println!("清空列表后 list = {:?}", list);
/* 尾部添加元素 */
list.push(1);
list.push(3);
list.push(2);
list.push(5);
list.push(4);
println!("添加元素后 list = {:?}", list);
/* 中间插入元素 */
list.insert(3, 6);
println!("在索引 3 处插入数字 6 ,得到 list = {:?}", list);
/* 删除元素 */
list.remove(3);
println!("删除索引 3 处的元素,得到 list = {:?}", list);
/* 通过索引遍历列表 */
let mut count = 0;
for _ in 0..list.len() {
count += 1;
}
/* 直接遍历列表元素 */
count = 0;
for _ in &list {
count += 1;
} // 或者
// list.iter().for_each(|_| count += 1);
// let count = list.iter().fold(0, |count, _| count + 1);
/* 拼接两个列表 */
let mut list1 = vec![6, 8, 7, 10, 9];
list.append(&mut list1); // append移动 之后 list1 为空!
// list.extend(&list1); // extend借用 list1 能继续使用
println!("将列表 list1 拼接到 list 之后,得到 list = {:?}", list);
/* 排序列表 */
list.sort();
println!("排序列表后 list = {:?}", list);
}

@ -26,6 +26,7 @@ let package = Package(
.executable(name: "binary_tree_bfs", targets: ["binary_tree_bfs"]),
.executable(name: "binary_tree_dfs", targets: ["binary_tree_dfs"]),
.executable(name: "binary_search_tree", targets: ["binary_search_tree"]),
.executable(name: "avl_tree", targets: ["avl_tree"]),
],
targets: [
.target(name: "utils", path: "utils"),
@ -50,5 +51,6 @@ let package = Package(
.executableTarget(name: "binary_tree_bfs", dependencies: ["utils"], path: "chapter_tree", sources: ["binary_tree_bfs.swift"]),
.executableTarget(name: "binary_tree_dfs", dependencies: ["utils"], path: "chapter_tree", sources: ["binary_tree_dfs.swift"]),
.executableTarget(name: "binary_search_tree", dependencies: ["utils"], path: "chapter_tree", sources: ["binary_search_tree.swift"]),
.executableTarget(name: "avl_tree", dependencies: ["utils"], path: "chapter_tree", sources: ["avl_tree.swift"]),
]
)

@ -0,0 +1,242 @@
/**
* File: avl_tree.swift
* Created Time: 2023-01-28
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
// Tree class
class AVLTree {
fileprivate var root: TreeNode? //
/* */
func height(node: TreeNode?) -> Int {
// -1 0
node == nil ? -1 : node!.height
}
/* */
private func updateHeight(node: TreeNode?) {
// + 1
node?.height = max(height(node: node?.left), height(node: node?.right)) + 1
}
/* */
func balanceFactor(node: TreeNode?) -> Int {
// 0
guard let node = node else { return 0 }
// = -
return height(node: node.left) - height(node: node.right)
}
/* */
private func rightRotate(node: TreeNode?) -> TreeNode? {
let child = node?.left
let grandChild = child?.right
// child node
child?.right = node
node?.left = grandChild
//
updateHeight(node: node)
updateHeight(node: child)
//
return child
}
/* */
private func leftRotate(node: TreeNode?) -> TreeNode? {
let child = node?.right
let grandChild = child?.left
// child node
child?.left = node
node?.right = grandChild
//
updateHeight(node: node)
updateHeight(node: child)
//
return child
}
/* 使 */
private func rotate(node: TreeNode?) -> TreeNode? {
// node
let balanceFactor = balanceFactor(node: node)
//
if balanceFactor > 1 {
if self.balanceFactor(node: node?.left) >= 0 {
//
return rightRotate(node: node)
} else {
//
node?.left = leftRotate(node: node?.left)
return rightRotate(node: node)
}
}
//
if balanceFactor < -1 {
if self.balanceFactor(node: node?.right) <= 0 {
//
return leftRotate(node: node)
} else {
//
node?.right = rightRotate(node: node?.right)
return leftRotate(node: node)
}
}
//
return node
}
/* */
@discardableResult
func insert(val: Int) -> TreeNode? {
root = insertHelper(node: root, val: val)
return root
}
/* */
private func insertHelper(node: TreeNode?, val: Int) -> TreeNode? {
var node = node
if node == nil {
return TreeNode(x: val)
}
/* 1. */
if val < node!.val {
node?.left = insertHelper(node: node?.left, val: val)
} else if val > node!.val {
node?.right = insertHelper(node: node?.right, val: val)
} else {
return node //
}
updateHeight(node: node) //
/* 2. 使 */
node = rotate(node: node)
//
return node
}
/* */
@discardableResult
func remove(val: Int) -> TreeNode? {
root = removeHelper(node: root, val: val)
return root
}
/* */
private func removeHelper(node: TreeNode?, val: Int) -> TreeNode? {
var node = node
if node == nil {
return nil
}
/* 1. */
if val < node!.val {
node?.left = removeHelper(node: node?.left, val: val)
} else if val > node!.val {
node?.right = removeHelper(node: node?.right, val: val)
} else {
if node?.left == nil || node?.right == nil {
let child = node?.left != nil ? node?.left : node?.right
// = 0 node
if child == nil {
return nil
}
// = 1 node
else {
node = child
}
} else {
// = 2
let temp = getInOrderNext(node: node?.right)
node?.right = removeHelper(node: node?.right, val: temp!.val)
node?.val = temp!.val
}
}
updateHeight(node: node) //
/* 2. 使 */
node = rotate(node: node)
//
return node
}
/* root */
private func getInOrderNext(node: TreeNode?) -> TreeNode? {
var node = node
if node == nil {
return node
}
// 访
while node?.left != nil {
node = node?.left
}
return node
}
/* */
func search(val: Int) -> TreeNode? {
var cur = root
while cur != nil {
// cur
if cur!.val < val {
cur = cur?.right
}
// cur
else if cur!.val > val {
cur = cur?.left
}
//
else {
break
}
}
//
return cur
}
}
@main
enum _AVLTree {
static func testInsert(tree: AVLTree, val: Int) {
tree.insert(val: val)
print("\n插入结点 \(val)AVL 树为")
PrintUtil.printTree(root: tree.root)
}
static func testRemove(tree: AVLTree, val: Int) {
tree.remove(val: val)
print("\n删除结点 \(val)AVL 树为")
PrintUtil.printTree(root: tree.root)
}
/* Driver Code */
static func main() {
/* AVL */
let avlTree = AVLTree()
/* */
// AVL
testInsert(tree: avlTree, val: 1)
testInsert(tree: avlTree, val: 2)
testInsert(tree: avlTree, val: 3)
testInsert(tree: avlTree, val: 4)
testInsert(tree: avlTree, val: 5)
testInsert(tree: avlTree, val: 8)
testInsert(tree: avlTree, val: 7)
testInsert(tree: avlTree, val: 9)
testInsert(tree: avlTree, val: 10)
testInsert(tree: avlTree, val: 6)
/* */
testInsert(tree: avlTree, val: 7)
/* */
// AVL
testRemove(tree: avlTree, val: 8) // 0
testRemove(tree: avlTree, val: 5) // 1
testRemove(tree: avlTree, val: 4) // 2
/* */
let node = avlTree.search(val: 7)
print("\n查找到的结点对象为 \(node!),结点值 = \(node!.val)")
}
}

@ -103,7 +103,18 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "Swift"
```swift title="avl_tree.swift"
/* AVL 树结点类 */
class TreeNode {
var val: Int // 结点值
var height: Int // 结点高度
var left: TreeNode? // 左子结点
var right: TreeNode? // 右子结点
init(x: Int) {
val = x
height = 0
}
}
```
「结点高度」是最远叶结点到该结点的距离,即走过的「边」的数量。需要特别注意,**叶结点的高度为 0 ,空结点的高度为 -1**。我们封装两个工具函数,分别用于获取与更新结点的高度。
@ -210,7 +221,17 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "Swift"
```swift title="avl_tree.swift"
/* 获取结点高度 */
func height(node: TreeNode?) -> Int {
// 空结点高度为 -1 ,叶结点高度为 0
node == nil ? -1 : node!.height
}
/* 更新结点高度 */
func updateHeight(node: TreeNode?) {
// 结点高度等于最高子树高度 + 1
node?.height = max(height(node: node?.left), height(node: node?.right)) + 1
}
```
### 结点平衡因子
@ -295,7 +316,13 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
=== "Swift"
```swift title="avl_tree.swift"
/* 获取平衡因子 */
func balanceFactor(node: TreeNode?) -> Int {
// 空结点平衡因子为 0
guard let node = node else { return 0 }
// 结点平衡因子 = 左子树高度 - 右子树高度
return height(node: node.left) - height(node: node.right)
}
```
!!! note
@ -427,7 +454,19 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
=== "Swift"
```swift title="avl_tree.swift"
/* 右旋操作 */
func rightRotate(node: TreeNode?) -> TreeNode? {
let child = node?.left
let grandChild = child?.right
// 以 child 为原点,将 node 向右旋转
child?.right = node
node?.left = grandChild
// 更新结点高度
updateHeight(node: node)
updateHeight(node: child)
// 返回旋转后子树的根节点
return child
}
```
### Case 2 - 左旋
@ -541,7 +580,19 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
=== "Swift"
```swift title="avl_tree.swift"
/* 左旋操作 */
func leftRotate(node: TreeNode?) -> TreeNode? {
let child = node?.right
let grandChild = child?.left
// 以 child 为原点,将 node 向左旋转
child?.left = node
node?.right = grandChild
// 更新结点高度
updateHeight(node: node)
updateHeight(node: child)
// 返回旋转后子树的根节点
return child
}
```
### Case 3 - 先左后右
@ -745,7 +796,35 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
=== "Swift"
```swift title="avl_tree.swift"
/* 执行旋转操作,使该子树重新恢复平衡 */
func rotate(node: TreeNode?) -> TreeNode? {
// 获取结点 node 的平衡因子
let balanceFactor = balanceFactor(node: node)
// 左偏树
if balanceFactor > 1 {
if self.balanceFactor(node: node?.left) >= 0 {
// 右旋
return rightRotate(node: node)
} else {
// 先左旋后右旋
node?.left = leftRotate(node: node?.left)
return rightRotate(node: node)
}
}
// 右偏树
if balanceFactor < -1 {
if self.balanceFactor(node: node?.right) <= 0 {
// 左旋
return leftRotate(node: node)
} else {
// 先右旋后左旋
node?.right = rightRotate(node: node?.right)
return leftRotate(node: node)
}
}
// 平衡树,无需旋转,直接返回
return node
}
```
## AVL 树常用操作
@ -894,7 +973,33 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
=== "Swift"
```swift title="avl_tree.swift"
/* 插入结点 */
@discardableResult
func insert(val: Int) -> TreeNode? {
root = insertHelper(node: root, val: val)
return root
}
/* 递归插入结点(辅助函数) */
func insertHelper(node: TreeNode?, val: Int) -> TreeNode? {
var node = node
if node == nil {
return TreeNode(x: val)
}
/* 1. 查找插入位置,并插入结点 */
if val < node!.val {
node?.left = insertHelper(node: node?.left, val: val)
} else if val > node!.val {
node?.right = insertHelper(node: node?.right, val: val)
} else {
return node // 重复结点不插入,直接返回
}
updateHeight(node: node) // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node: node)
// 返回子树的根节点
return node
}
```
### 删除结点
@ -1100,7 +1205,48 @@ AVL 树的独特之处在于「旋转 Rotation」的操作其可 **在不影
=== "Swift"
```swift title="avl_tree.swift"
/* 删除结点 */
@discardableResult
func remove(val: Int) -> TreeNode? {
root = removeHelper(node: root, val: val)
return root
}
/* 递归删除结点(辅助函数) */
func removeHelper(node: TreeNode?, val: Int) -> TreeNode? {
var node = node
if node == nil {
return nil
}
/* 1. 查找结点,并删除之 */
if val < node!.val {
node?.left = removeHelper(node: node?.left, val: val)
} else if val > node!.val {
node?.right = removeHelper(node: node?.right, val: val)
} else {
if node?.left == nil || node?.right == nil {
let child = node?.left != nil ? node?.left : node?.right
// 子结点数量 = 0 ,直接删除 node 并返回
if child == nil {
return nil
}
// 子结点数量 = 1 ,直接删除 node
else {
node = child
}
} else {
// 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点
let temp = getInOrderNext(node: node?.right)
node?.right = removeHelper(node: node?.right, val: temp!.val)
node?.val = temp!.val
}
}
updateHeight(node: node) // 更新结点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node: node)
// 返回子树的根节点
return node
}
```
### 查找结点

Loading…
Cancel
Save