Bug fixes to C code.

This commit is contained in:
krahets
2023-11-01 05:14:22 +08:00
parent f7dd05e7a4
commit 355cc3a6b1
31 changed files with 246 additions and 219 deletions

View File

@ -82,5 +82,7 @@ int main() {
int index = find(n0, 2);
printf("链表中值为 2 的节点的索引 = %d\r\n", index);
// 释放内存
freeMemoryLinkedList(n0);
return 0;
}

View File

@ -79,7 +79,7 @@ void insert(MyList *nums, int index, int num) {
/* 删除元素 */
// 注意stdio.h 占用了 remove 关键词
int removeNum(MyList *nums, int index) {
int removeItem(MyList *nums, int index) {
assert(index >= 0 && index < size(nums));
int num = nums->arr[index];
for (int i = index; i < size(nums) - 1; i++) {
@ -133,7 +133,7 @@ int main() {
printArray(toArray(nums), size(nums));
/* 删除元素 */
removeNum(nums, 3);
removeItem(nums, 3);
printf("删除索引 3 处的元素,得到 nums = ");
printArray(toArray(nums), size(nums));

View File

@ -56,5 +56,6 @@ int main() {
printf("构建的二叉树为:\n");
printTree(root);
freeMemoryTree(root);
return 0;
}

View File

@ -28,6 +28,11 @@ GraphAdjMat *newGraphAdjMat() {
return graph;
}
/* 析构函数 */
void delGraphAdjMat(GraphAdjMat *graph) {
free(graph);
}
/* 添加顶点 */
void addVertex(GraphAdjMat *graph, int val) {
if (graph->size == MAX_SIZE) {
@ -139,7 +144,7 @@ int main() {
printGraphAdjMat(graph);
// 释放内存
free(graph);
delGraphAdjMat(graph);
return 0;
}

View File

@ -7,7 +7,7 @@
#include "../utils/common.h"
/* 哈希表默认大小 */
#define HASH_MAP_DEFAULT_SIZE 100
#define HASHTABLE_CAPACITY 100
/* 键值对 int->string */
typedef struct {
@ -23,131 +23,133 @@ typedef struct {
/* 基于数组简易实现的哈希表 */
typedef struct {
Pair *buckets[HASH_MAP_DEFAULT_SIZE];
Pair *buckets[HASHTABLE_CAPACITY];
} ArrayHashMap;
/* 哈希表初始化函数 */
/* 构造函数 */
ArrayHashMap *newArrayHashMap() {
ArrayHashMap *map = malloc(sizeof(ArrayHashMap));
return map;
ArrayHashMap *hmap = malloc(sizeof(ArrayHashMap));
return hmap;
}
/* 析构函数 */
void delArrayHashMap(ArrayHashMap *hmap) {
for (int i = 0; i < HASHTABLE_CAPACITY; i++) {
if (hmap->buckets[i] != NULL) {
free(hmap->buckets[i]->val);
free(hmap->buckets[i]);
}
}
free(hmap);
}
/* 哈希函数 */
int hashFunc(int key) {
int index = key % HASH_MAP_DEFAULT_SIZE;
int index = key % HASHTABLE_CAPACITY;
return index;
}
/* 查询操作 */
const char *get(const ArrayHashMap *d, const int key) {
const char *get(const ArrayHashMap *hmap, const int key) {
int index = hashFunc(key);
const Pair *Pair = d->buckets[index];
const Pair *Pair = hmap->buckets[index];
if (Pair == NULL)
return NULL;
return Pair->val;
}
/* 添加操作 */
void put(ArrayHashMap *d, const int key, const char *val) {
void put(ArrayHashMap *hmap, const int key, const char *val) {
Pair *Pair = malloc(sizeof(Pair));
Pair->key = key;
Pair->val = malloc(strlen(val) + 1);
strcpy(Pair->val, val);
int index = hashFunc(key);
d->buckets[index] = Pair;
hmap->buckets[index] = Pair;
}
/* 删除操作 */
void removeItem(ArrayHashMap *d, const int key) {
void removeItem(ArrayHashMap *hmap, const int key) {
int index = hashFunc(key);
free(d->buckets[index]->val);
free(d->buckets[index]);
d->buckets[index] = NULL;
free(hmap->buckets[index]->val);
free(hmap->buckets[index]);
hmap->buckets[index] = NULL;
}
/* 获取所有键值对 */
void pairSet(ArrayHashMap *d, MapSet *set) {
void pairSet(ArrayHashMap *hmap, MapSet *set) {
Pair *entries;
int i = 0, index = 0;
int total = 0;
/* 统计有效键值对数量 */
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
if (hmap->buckets[i] != NULL) {
total++;
}
}
entries = malloc(sizeof(Pair) * total);
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
entries[index].key = d->buckets[i]->key;
entries[index].val = malloc(strlen(d->buckets[i]->val + 1));
strcpy(entries[index].val, d->buckets[i]->val);
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
if (hmap->buckets[i] != NULL) {
entries[index].key = hmap->buckets[i]->key;
entries[index].val = malloc(strlen(hmap->buckets[i]->val + 1));
strcpy(entries[index].val, hmap->buckets[i]->val);
index++;
}
}
set->set = entries;
set->len = total;
}
/* 获取所有键 */
void keySet(ArrayHashMap *d, MapSet *set) {
void keySet(ArrayHashMap *hmap, MapSet *set) {
int *keys;
int i = 0, index = 0;
int total = 0;
/* 统计有效键值对数量 */
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
if (hmap->buckets[i] != NULL) {
total++;
}
}
keys = malloc(total * sizeof(int));
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
keys[index] = d->buckets[i]->key;
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
if (hmap->buckets[i] != NULL) {
keys[index] = hmap->buckets[i]->key;
index++;
}
}
set->set = keys;
set->len = total;
}
/* 获取所有值 */
void valueSet(ArrayHashMap *d, MapSet *set) {
void valueSet(ArrayHashMap *hmap, MapSet *set) {
char **vals;
int i = 0, index = 0;
int total = 0;
/* 统计有效键值对数量 */
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
if (hmap->buckets[i] != NULL) {
total++;
}
}
vals = malloc(total * sizeof(char *));
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
vals[index] = d->buckets[i]->val;
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
if (hmap->buckets[i] != NULL) {
vals[index] = hmap->buckets[i]->val;
index++;
}
}
set->set = vals;
set->len = total;
}
/* 打印哈希表 */
void print(ArrayHashMap *d) {
void print(ArrayHashMap *hmap) {
int i;
MapSet set;
pairSet(d, &set);
pairSet(hmap, &set);
Pair *entries = (Pair *)set.set;
for (i = 0; i < set.len; i++) {
printf("%d -> %s\n", entries[i].key, entries[i].val);
@ -158,38 +160,38 @@ void print(ArrayHashMap *d) {
/* Driver Code */
int main() {
/* 初始化哈希表 */
ArrayHashMap *map = newArrayHashMap();
ArrayHashMap *hmap = newArrayHashMap();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
put(map, 12836, "小哈");
put(map, 15937, "小啰");
put(map, 16750, "小算");
put(map, 13276, "小法");
put(map, 10583, "小鸭");
put(hmap, 12836, "小哈");
put(hmap, 15937, "小啰");
put(hmap, 16750, "小算");
put(hmap, 13276, "小法");
put(hmap, 10583, "小鸭");
printf("\n添加完成后,哈希表为\nKey -> Value\n");
print(map);
print(hmap);
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
const char *name = get(map, 15937);
const char *name = get(hmap, 15937);
printf("\n输入学号 15937 ,查询到姓名 %s\n", name);
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
removeItem(map, 10583);
removeItem(hmap, 10583);
printf("\n删除 10583 后,哈希表为\nKey -> Value\n");
print(map);
print(hmap);
/* 遍历哈希表 */
int i;
printf("\n遍历键值对 Key->Value\n");
print(map);
print(hmap);
MapSet set;
keySet(map, &set);
keySet(hmap, &set);
int *keys = (int *)set.set;
printf("\n单独遍历键 Key\n");
for (i = 0; i < set.len; i++) {
@ -197,7 +199,7 @@ int main() {
}
free(set.set);
valueSet(map, &set);
valueSet(hmap, &set);
char **vals = (char **)set.set;
printf("\n单独遍历键 Value\n");
for (i = 0; i < set.len; i++) {
@ -205,5 +207,6 @@ int main() {
}
free(set.set);
delArrayHashMap(hmap);
return 0;
}

View File

@ -33,7 +33,7 @@ typedef struct {
} HashMapChaining;
/* 构造函数 */
HashMapChaining *initHashMapChaining() {
HashMapChaining *newHashMapChaining() {
HashMapChaining *hashMap = (HashMapChaining *)malloc(sizeof(HashMapChaining));
hashMap->size = 0;
hashMap->capacity = 4;
@ -47,14 +47,14 @@ HashMapChaining *initHashMapChaining() {
}
/* 析构函数 */
void freeHashMapChaining(HashMapChaining *hashMap) {
void delHashMapChaining(HashMapChaining *hashMap) {
for (int i = 0; i < hashMap->capacity; i++) {
Node *cur = hashMap->buckets[i];
while (cur) {
Node *temp = cur;
Node *tmp = cur;
cur = cur->next;
free(temp->pair);
free(temp);
free(tmp->pair);
free(tmp);
}
}
free(hashMap->buckets);
@ -144,7 +144,7 @@ void put(HashMapChaining *hashMap, int key, const char *val) {
}
/* 删除操作 */
void removeKey(HashMapChaining *hashMap, int key) {
void removeItem(HashMapChaining *hashMap, int key) {
int index = hashFunc(hashMap, key);
Node *cur = hashMap->buckets[index];
Node *pre = NULL;
@ -183,7 +183,7 @@ void print(HashMapChaining *hashMap) {
/* Driver Code */
int main() {
/* 初始化哈希表 */
HashMapChaining *hashMap = initHashMapChaining();
HashMapChaining *hashMap = newHashMapChaining();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
@ -202,12 +202,12 @@ int main() {
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
removeKey(hashMap, 12836);
removeItem(hashMap, 12836);
printf("\n删除学号 12836 后,哈希表为\nKey -> Value\n");
print(hashMap);
/* 释放哈希表空间 */
freeHashMapChaining(hashMap);
delHashMapChaining(hashMap);
return 0;
}

View File

@ -17,111 +17,111 @@ typedef struct {
} MaxHeap;
// 函数声明
void siftDown(MaxHeap *h, int i);
void siftUp(MaxHeap *h, int i);
int parent(MaxHeap *h, int i);
void siftDown(MaxHeap *maxHeap, int i);
void siftUp(MaxHeap *maxHeap, int i);
int parent(MaxHeap *maxHeap, int i);
/* 构造函数,根据切片建堆 */
MaxHeap *newMaxHeap(int nums[], int size) {
// 所有元素入堆
MaxHeap *h = (MaxHeap *)malloc(sizeof(MaxHeap));
h->size = size;
memcpy(h->data, nums, size * sizeof(int));
for (int i = parent(h, size - 1); i >= 0; i--) {
MaxHeap *maxHeap = (MaxHeap *)malloc(sizeof(MaxHeap));
maxHeap->size = size;
memcpy(maxHeap->data, nums, size * sizeof(int));
for (int i = parent(maxHeap, size - 1); i >= 0; i--) {
// 堆化除叶节点以外的其他所有节点
siftDown(h, i);
siftDown(maxHeap, i);
}
return h;
return maxHeap;
}
/* 析构函数 */
void freeMaxHeap(MaxHeap *h) {
void delMaxHeap(MaxHeap *maxHeap) {
// 释放内存
free(h);
free(maxHeap);
}
/* 获取左子节点索引 */
int left(MaxHeap *h, int i) {
int left(MaxHeap *maxHeap, int i) {
return 2 * i + 1;
}
/* 获取右子节点索引 */
int right(MaxHeap *h, int i) {
int right(MaxHeap *maxHeap, int i) {
return 2 * i + 2;
}
/* 获取父节点索引 */
int parent(MaxHeap *h, int i) {
int parent(MaxHeap *maxHeap, int i) {
return (i - 1) / 2;
}
/* 交换元素 */
void swap(MaxHeap *h, int i, int j) {
int temp = h->data[i];
h->data[i] = h->data[j];
h->data[j] = temp;
void swap(MaxHeap *maxHeap, int i, int j) {
int temp = maxHeap->data[i];
maxHeap->data[i] = maxHeap->data[j];
maxHeap->data[j] = temp;
}
/* 获取堆大小 */
int size(MaxHeap *h) {
return h->size;
int size(MaxHeap *maxHeap) {
return maxHeap->size;
}
/* 判断堆是否为空 */
int isEmpty(MaxHeap *h) {
return h->size == 0;
int isEmpty(MaxHeap *maxHeap) {
return maxHeap->size == 0;
}
/* 访问堆顶元素 */
int peek(MaxHeap *h) {
return h->data[0];
int peek(MaxHeap *maxHeap) {
return maxHeap->data[0];
}
/* 元素入堆 */
void push(MaxHeap *h, int val) {
void push(MaxHeap *maxHeap, int val) {
// 默认情况下,不应该添加这么多节点
if (h->size == MAX_SIZE) {
if (maxHeap->size == MAX_SIZE) {
printf("heap is full!");
return;
}
// 添加节点
h->data[h->size] = val;
h->size++;
maxHeap->data[maxHeap->size] = val;
maxHeap->size++;
// 从底至顶堆化
siftUp(h, h->size - 1);
siftUp(maxHeap, maxHeap->size - 1);
}
/* 元素出堆 */
int pop(MaxHeap *h) {
int pop(MaxHeap *maxHeap) {
// 判空处理
if (isEmpty(h)) {
if (isEmpty(maxHeap)) {
printf("heap is empty!");
return INT_MAX;
}
// 交换根节点与最右叶节点(即交换首元素与尾元素)
swap(h, 0, size(h) - 1);
swap(maxHeap, 0, size(maxHeap) - 1);
// 删除节点
int val = h->data[h->size - 1];
h->size--;
int val = maxHeap->data[maxHeap->size - 1];
maxHeap->size--;
// 从顶至底堆化
siftDown(h, 0);
siftDown(maxHeap, 0);
// 返回堆顶元素
return val;
}
/* 从节点 i 开始,从顶至底堆化 */
void siftDown(MaxHeap *h, int i) {
void siftDown(MaxHeap *maxHeap, int i) {
while (true) {
// 判断节点 i, l, r 中值最大的节点,记为 max
int l = left(h, i);
int r = right(h, i);
int l = left(maxHeap, i);
int r = right(maxHeap, i);
int max = i;
if (l < size(h) && h->data[l] > h->data[max]) {
if (l < size(maxHeap) && maxHeap->data[l] > maxHeap->data[max]) {
max = l;
}
if (r < size(h) && h->data[r] > h->data[max]) {
if (r < size(maxHeap) && maxHeap->data[r] > maxHeap->data[max]) {
max = r;
}
// 若节点 i 最大或索引 l, r 越界,则无须继续堆化,跳出
@ -129,23 +129,23 @@ void siftDown(MaxHeap *h, int i) {
break;
}
// 交换两节点
swap(h, i, max);
swap(maxHeap, i, max);
// 循环向下堆化
i = max;
}
}
/* 从节点 i 开始,从底至顶堆化 */
void siftUp(MaxHeap *h, int i) {
void siftUp(MaxHeap *maxHeap, int i) {
while (true) {
// 获取节点 i 的父节点
int p = parent(h, i);
int p = parent(maxHeap, i);
// 当“越过根节点”或“节点无须修复”时,结束堆化
if (p < 0 || h->data[i] <= h->data[p]) {
if (p < 0 || maxHeap->data[i] <= maxHeap->data[p]) {
break;
}
// 交换两节点
swap(h, i, p);
swap(maxHeap, i, p);
// 循环向上堆化
i = p;
}

View File

@ -11,31 +11,31 @@ int main() {
/* 初始化堆 */
// 初始化大顶堆
int nums[] = {9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2};
MaxHeap *heap = newMaxHeap(nums, sizeof(nums) / sizeof(int));
MaxHeap *maxHeap = newMaxHeap(nums, sizeof(nums) / sizeof(int));
printf("输入数组并建堆后\n");
printHeap(heap->data, heap->size);
printHeap(maxHeap->data, maxHeap->size);
/* 获取堆顶元素 */
printf("\n堆顶元素为 %d\n", peek(heap));
printf("\n堆顶元素为 %d\n", peek(maxHeap));
/* 元素入堆 */
push(heap, 7);
push(maxHeap, 7);
printf("\n元素 7 入堆后\n");
printHeap(heap->data, heap->size);
printHeap(maxHeap->data, maxHeap->size);
/* 堆顶元素出堆 */
int top = pop(heap);
int top = pop(maxHeap);
printf("\n堆顶元素 %d 出堆后\n", top);
printHeap(heap->data, heap->size);
printHeap(maxHeap->data, maxHeap->size);
/* 获取堆大小 */
printf("\n堆元素数量为 %d\n", size(heap));
printf("\n堆元素数量为 %d\n", size(maxHeap));
/* 判断堆是否为空 */
printf("\n堆是否为空 %d\n", isEmpty(heap));
printf("\n堆是否为空 %d\n", isEmpty(maxHeap));
// 释放内存
freeMaxHeap(heap);
delMaxHeap(maxHeap);
return 0;
}

View File

@ -54,7 +54,7 @@ int *topKHeap(int *nums, int sizeNums, int k) {
}
int *res = getMinHeap(maxHeap);
// 释放内存
freeMaxHeap(maxHeap);
delMaxHeap(maxHeap);
return res;
}

View File

@ -62,5 +62,6 @@ int main() {
index = binarySearchRightEdge(nums, sizeof(nums) / sizeof(nums[0]), targets[i]);
printf("最右一个元素 %d 的索引为 %d\n", targets[i], index);
}
return 0;
}

View File

@ -27,7 +27,7 @@ ArrayDeque *newArrayDeque(int capacity) {
/* 析构函数 */
void delArrayDeque(ArrayDeque *deque) {
free(deque->nums);
deque->queCapacity = 0;
free(deque);
}
/* 获取双向队列的容量 */

View File

@ -27,7 +27,7 @@ ArrayQueue *newArrayQueue(int capacity) {
/* 析构函数 */
void delArrayQueue(ArrayQueue *queue) {
free(queue->nums);
queue->queCapacity = 0;
free(queue);
}
/* 获取队列的容量 */

View File

@ -16,50 +16,56 @@ typedef struct {
/* 构造函数 */
ArrayStack *newArrayStack() {
ArrayStack *s = malloc(sizeof(ArrayStack));
ArrayStack *stack = malloc(sizeof(ArrayStack));
// 初始化一个大容量,避免扩容
s->data = malloc(sizeof(int) * MAX_SIZE);
s->size = 0;
return s;
stack->data = malloc(sizeof(int) * MAX_SIZE);
stack->size = 0;
return stack;
}
/* 析构函数 */
void delArrayStack(ArrayStack *stack) {
free(stack->data);
free(stack);
}
/* 获取栈的长度 */
int size(ArrayStack *s) {
return s->size;
int size(ArrayStack *stack) {
return stack->size;
}
/* 判断栈是否为空 */
bool isEmpty(ArrayStack *s) {
return s->size == 0;
bool isEmpty(ArrayStack *stack) {
return stack->size == 0;
}
/* 入栈 */
void push(ArrayStack *s, int num) {
if (s->size == MAX_SIZE) {
void push(ArrayStack *stack, int num) {
if (stack->size == MAX_SIZE) {
printf("stack is full.\n");
return;
}
s->data[s->size] = num;
s->size++;
stack->data[stack->size] = num;
stack->size++;
}
/* 访问栈顶元素 */
int peek(ArrayStack *s) {
if (s->size == 0) {
int peek(ArrayStack *stack) {
if (stack->size == 0) {
printf("stack is empty.\n");
return INT_MAX;
}
return s->data[s->size - 1];
return stack->data[stack->size - 1];
}
/* 出栈 */
int pop(ArrayStack *s) {
if (s->size == 0) {
int pop(ArrayStack *stack) {
if (stack->size == 0) {
printf("stack is empty.\n");
return INT_MAX;
}
int val = peek(s);
s->size--;
int val = peek(stack);
stack->size--;
return val;
}
@ -92,11 +98,10 @@ int main() {
/* 判断是否为空 */
bool empty = isEmpty(stack);
printf("栈是否为空 = %s\n", empty ? "true" : "false");
printf("栈是否为空 = %stack\n", empty ? "true" : "false");
// 释放内存
free(stack->data);
free(stack);
delArrayStack(stack);
return 0;
}

View File

@ -13,7 +13,7 @@ typedef struct {
} ArrayBinaryTree;
/* 构造函数 */
ArrayBinaryTree *createArrayBinaryTree(int *arr, int arrSize) {
ArrayBinaryTree *newArrayBinaryTree(int *arr, int arrSize) {
ArrayBinaryTree *abt = (ArrayBinaryTree *)malloc(sizeof(ArrayBinaryTree));
abt->tree = malloc(sizeof(int) * arrSize);
memcpy(abt->tree, arr, sizeof(int) * arrSize);
@ -21,6 +21,12 @@ ArrayBinaryTree *createArrayBinaryTree(int *arr, int arrSize) {
return abt;
}
/* 析构函数 */
void delArrayBinaryTree(ArrayBinaryTree *abt) {
free(abt->tree);
free(abt);
}
/* 节点数量 */
int size(ArrayBinaryTree *abt) {
return abt->size;
@ -120,7 +126,7 @@ int main() {
printf("二叉树的链表表示:\n");
printTree(root);
ArrayBinaryTree *abt = createArrayBinaryTree(arr, arrSize);
ArrayBinaryTree *abt = newArrayBinaryTree(arr, arrSize);
// 访问节点
int i = 1;
@ -155,8 +161,6 @@ int main() {
free(res);
// 释放内存
freeMemoryTree(root);
free(abt);
delArrayBinaryTree(abt);
return 0;
}

View File

@ -6,18 +6,24 @@
#include "../utils/common.h"
/* AVL Tree */
/* AVL 树结构体 */
typedef struct {
TreeNode *root;
} AVLTree;
/* 构建 AVL 树 */
/* 构造函数 */
AVLTree *newAVLTree() {
AVLTree *tree = (AVLTree *)malloc(sizeof(AVLTree));
tree->root = NULL;
return tree;
}
/* 析构函数 */
void delAVLTree(AVLTree *tree) {
freeMemoryTree(tree->root);
free(tree);
}
/* 获取节点高度 */
int height(TreeNode *node) {
// 空节点高度为 -1 ,叶节点高度为 0
@ -247,5 +253,7 @@ int main() {
TreeNode *node = search(tree, 7);
printf("\n查找到的节点对象节点值 = %d \n", node->val);
// 释放内存
delAVLTree(tree);
return 0;
}

View File

@ -6,41 +6,25 @@
#include "../utils/common.h"
/* 二叉搜索树 */
/* 二叉搜索树你结构体 */
typedef struct {
TreeNode *root;
} BinarySearchTree;
/* 比较器:从小到大排序 */
int sortIntHelper(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
/* 构建二叉搜索树 */
TreeNode *buildTree(int nums[], int i, int j) {
if (i > j) {
return NULL;
}
// 将数组中间节点作为根节点
int mid = (i + j) / 2;
TreeNode *root = newTreeNode(nums[mid]);
// 递归建立左子树和右子树
root->left = buildTree(nums, i, mid - 1);
root->right = buildTree(nums, mid + 1, j);
return root;
}
BinarySearchTree *newBinarySearchTree(int nums[], int size) {
/* 构造函数 */
BinarySearchTree *newBinarySearchTree() {
// 初始化空树
BinarySearchTree *bst = (BinarySearchTree *)malloc(sizeof(BinarySearchTree));
TreeNode *root;
// 从小到大排序数组
qsort(nums, size, sizeof(int), sortIntHelper);
// 构建二叉搜索树
root = buildTree(nums, 0, size - 1);
bst->root = root;
bst->root = NULL;
return bst;
}
/* 析构函数 */
void delBinarySearchTree(BinarySearchTree *bst) {
freeMemoryTree(bst->root);
free(bst);
}
/* 获取二叉树根节点 */
TreeNode *getRoot(BinarySearchTree *bst) {
return bst->root;
@ -151,8 +135,11 @@ void removeItem(BinarySearchTree *bst, int num) {
/* Driver Code */
int main() {
/* 初始化二叉搜索树 */
int nums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
BinarySearchTree *bst = newBinarySearchTree(nums, sizeof(nums) / sizeof(int));
int nums[] = {8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15};
BinarySearchTree *bst = newBinarySearchTree();
for (int i = 0; i < sizeof(nums) / sizeof(int); i++) {
insert(bst, nums[i]);
}
printf("初始化的二叉树为\n");
printTree(getRoot(bst));
@ -177,7 +164,6 @@ int main() {
printTree(getRoot(bst));
// 释放内存
free(bst);
delBinarySearchTree(bst);
return 0;
}

View File

@ -38,5 +38,6 @@ int main() {
printf("删除节点 P 后\n");
printTree(n1);
freeMemoryTree(n1);
return 0;
}

View File

@ -9,7 +9,7 @@
#define MAX_SIZE 100
// 辅助数组,用于存储遍历序列
int *arr;
int arr[MAX_SIZE];
/* 前序遍历 */
void preOrder(TreeNode *root, int *size) {
@ -53,7 +53,6 @@ int main() {
/* 前序遍历 */
// 初始化辅助数组
arr = (int *)malloc(sizeof(int) * MAX_SIZE);
size = 0;
preOrder(root, &size);
printf("前序遍历的节点打印序列 = ");
@ -71,5 +70,6 @@ int main() {
printf("后序遍历的节点打印序列 = ");
printArray(arr, size);
freeMemoryTree(root);
return 0;
}

View File

@ -49,6 +49,17 @@ ListNode *getListNode(ListNode *head, int val) {
return head;
}
/* Free the memory allocated to a linked list */
void freeMemoryLinkedList(ListNode *cur) {
// 释放内存
ListNode *pre;
while (cur != NULL) {
pre = cur;
cur = cur->next;
free(pre);
}
}
#ifdef __cplusplus
}
#endif

View File

@ -95,7 +95,7 @@ void showTrunks(Trunk *trunk) {
}
/* Help to print a binary tree, hide more details */
static void printTreeHelper(TreeNode *node, Trunk *prev, bool isLeft) {
static void printTreeHelper(TreeNode *node, Trunk *prev, bool isRight) {
if (node == NULL) {
return;
}
@ -104,7 +104,7 @@ static void printTreeHelper(TreeNode *node, Trunk *prev, bool isLeft) {
printTreeHelper(node->right, trunk, true);
if (prev == NULL) {
trunk->str = "———";
} else if (isLeft) {
} else if (isRight) {
trunk->str = "/———";
prev_str = " |";
} else {

View File

@ -109,7 +109,7 @@ void showTrunks(Trunk *p) {
}
/* Print a binary tree */
void printTree(TreeNode *root, Trunk *prev, bool isLeft) {
void printTree(TreeNode *root, Trunk *prev, bool isRight) {
if (root == nullptr) {
return;
}
@ -121,7 +121,7 @@ void printTree(TreeNode *root, Trunk *prev, bool isLeft) {
if (!prev) {
trunk.str = "———";
} else if (isLeft) {
} else if (isRight) {
trunk.str = "/———";
prev_str = " |";
} else {

View File

@ -64,7 +64,7 @@ public static class PrintUtil {
}
/* Print a binary tree */
public static void PrintTree(TreeNode? root, Trunk? prev, bool isLeft) {
public static void PrintTree(TreeNode? root, Trunk? prev, bool isRight) {
if (root == null) {
return;
}
@ -76,7 +76,7 @@ public static class PrintUtil {
if (prev == null) {
trunk.str = "———";
} else if (isLeft) {
} else if (isRight) {
trunk.str = "/———";
prev_str = " |";
} else {

View File

@ -42,7 +42,7 @@ void printLinkedList(ListNode? head) {
* This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
void printTree(TreeNode? root, [Trunk? prev = null, bool isLeft = false]) {
void printTree(TreeNode? root, [Trunk? prev = null, bool isRight = false]) {
if (root == null) {
return;
}
@ -54,7 +54,7 @@ void printTree(TreeNode? root, [Trunk? prev = null, bool isLeft = false]) {
if (prev == null) {
trunk.str = '———';
} else if (isLeft) {
} else if (isRight) {
trunk.str = '/———';
prev_str = ' |';
} else {

View File

@ -71,7 +71,7 @@ func PrintTree(root *TreeNode) {
// printTreeHelper Help to print a binary tree, hide more details
// This tree printer is borrowed from TECHIE DELIGHT
// https://www.techiedelight.com/c-program-print-binary-tree/
func printTreeHelper(root *TreeNode, prev *trunk, isLeft bool) {
func printTreeHelper(root *TreeNode, prev *trunk, isRight bool) {
if root == nil {
return
}
@ -80,7 +80,7 @@ func printTreeHelper(root *TreeNode, prev *trunk, isLeft bool) {
printTreeHelper(root.Right, trunk, true)
if prev == nil {
trunk.str = "———"
} else if isLeft {
} else if isRight {
trunk.str = "/———"
prevStr = " |"
} else {

View File

@ -58,7 +58,7 @@ public class PrintUtil {
}
/* Print a binary tree */
public static void printTree(TreeNode root, Trunk prev, boolean isLeft) {
public static void printTree(TreeNode root, Trunk prev, boolean isRight) {
if (root == null) {
return;
}
@ -70,7 +70,7 @@ public class PrintUtil {
if (prev == null) {
trunk.str = "———";
} else if (isLeft) {
} else if (isRight) {
trunk.str = "/———";
prev_str = " |";
} else {

View File

@ -38,9 +38,9 @@ function printTree(root) {
* Print a binary tree
* @param root
* @param prev
* @param isLeft
* @param isRight
*/
function printTree(root, prev, isLeft) {
function printTree(root, prev, isRight) {
if (root === null) {
return;
}
@ -52,7 +52,7 @@ function printTree(root, prev, isLeft) {
if (!prev) {
trunk.str = '———';
} else if (isLeft) {
} else if (isRight) {
trunk.str = '/———';
prev_str = ' |';
} else {

View File

@ -35,7 +35,7 @@ def show_trunks(p: Trunk | None):
print(p.str, end="")
def print_tree(root: TreeNode | None, prev: Trunk | None = None, is_left: bool = False):
def print_tree(root: TreeNode | None, prev: Trunk | None = None, is_right: bool = False):
"""
Print a binary tree
This tree printer is borrowed from TECHIE DELIGHT
@ -50,7 +50,7 @@ def print_tree(root: TreeNode | None, prev: Trunk | None = None, is_left: bool =
if prev is None:
trunk.str = "———"
elif is_left:
elif is_right:
trunk.str = "/———"
prev_str = " |"
else:

View File

@ -57,7 +57,7 @@ pub fn print_tree(root: &Rc<RefCell<TreeNode>>) {
_print_tree(Some(root), None, false);
}
fn _print_tree(root: Option<&Rc<RefCell<TreeNode>>>, prev: Option<&Trunk>, is_left: bool) {
fn _print_tree(root: Option<&Rc<RefCell<TreeNode>>>, prev: Option<&Trunk>, is_right: bool) {
if let Some(node) = root {
let mut prev_str = " ";
let trunk = Trunk { prev, str: Cell::new(prev_str) };
@ -65,7 +65,7 @@ fn _print_tree(root: Option<&Rc<RefCell<TreeNode>>>, prev: Option<&Trunk>, is_le
if prev.is_none() {
trunk.str.set("———");
} else if is_left {
} else if is_right {
trunk.str.set("/———");
prev_str = " |";
} else {

View File

@ -26,10 +26,10 @@ public enum PrintUtil {
}
public static func printTree(root: TreeNode?) {
printTree(root: root, prev: nil, isLeft: false)
printTree(root: root, prev: nil, isRight: false)
}
private static func printTree(root: TreeNode?, prev: Trunk?, isLeft: Bool) {
private static func printTree(root: TreeNode?, prev: Trunk?, isRight: Bool) {
if root == nil {
return
}
@ -37,11 +37,11 @@ public enum PrintUtil {
var prevStr = " "
let trunk = Trunk(prev: prev, str: prevStr)
printTree(root: root?.right, prev: trunk, isLeft: true)
printTree(root: root?.right, prev: trunk, isRight: true)
if prev == nil {
trunk.str = "———"
} else if isLeft {
} else if isRight {
trunk.str = "/———"
prevStr = " |"
} else {
@ -57,7 +57,7 @@ public enum PrintUtil {
}
trunk.str = " |"
printTree(root: root?.left, prev: trunk, isLeft: false)
printTree(root: root?.left, prev: trunk, isRight: false)
}
private static func showTrunks(p: Trunk?) {

View File

@ -44,12 +44,12 @@ function printTree(root: TreeNode | null) {
* Print a binary tree
* @param root
* @param prev
* @param isLeft
* @param isRight
*/
function printTreeHelper(
root: TreeNode | null,
prev: Trunk | null,
isLeft: boolean
isRight: boolean
) {
if (root === null) {
return;
@ -62,7 +62,7 @@ function printTreeHelper(
if (prev === null) {
trunk.str = '———';
} else if (isLeft) {
} else if (isRight) {
trunk.str = '/———';
prev_str = ' |';
} else {

View File

@ -101,7 +101,7 @@ pub fn showTrunks(p: ?*Trunk) void {
// The interface of the tree printer
// Print a binary tree
pub fn printTree(root: ?*TreeNode(i32), prev: ?*Trunk, isLeft: bool) !void {
pub fn printTree(root: ?*TreeNode(i32), prev: ?*Trunk, isRight: bool) !void {
if (root == null) {
return;
}
@ -113,7 +113,7 @@ pub fn printTree(root: ?*TreeNode(i32), prev: ?*Trunk, isLeft: bool) !void {
if (prev == null) {
trunk.str = "———";
} else if (isLeft) {
} else if (isRight) {
trunk.str = "/———";
prev_str = " |";
} else {