mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-16 13:40:58 +00:00
refactor: Replace vector with array in C code (#894)
* Re-implement merge sort function. * Replace vector with array for C. * fix
This commit is contained in:
@@ -6,22 +6,20 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
vector *res;
|
||||
// 假设结果长度不超过 100
|
||||
#define MAX_SIZE 100
|
||||
|
||||
// 打印向量中的元素
|
||||
void printFunc(vector *v, void *p) {
|
||||
TreeNode *node = p;
|
||||
printf("%d ", node->val);
|
||||
}
|
||||
TreeNode *res[MAX_SIZE];
|
||||
int resSize = 0;
|
||||
|
||||
/* 前序遍历:例题一 */
|
||||
void preOrder(TreeNode *root) {
|
||||
static void preOrder(TreeNode *root) {
|
||||
if (root == NULL) {
|
||||
return;
|
||||
}
|
||||
if (root->val == 7) {
|
||||
// 记录解
|
||||
vectorPushback(res, root, sizeof(int));
|
||||
res[resSize++] = root;
|
||||
}
|
||||
preOrder(root->left);
|
||||
preOrder(root->right);
|
||||
@@ -30,15 +28,21 @@ void preOrder(TreeNode *root) {
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int arr[] = {1, 7, 3, 4, 5, 6, 7};
|
||||
res = newVector();
|
||||
TreeNode *root = arrToTree(arr, sizeof(arr) / sizeof(arr[0]));
|
||||
printf("\n初始化二叉树\r\n");
|
||||
TreeNode *root = arrayToTree(arr, sizeof(arr) / sizeof(arr[0]));
|
||||
printf("\n初始化二叉树\n");
|
||||
printTree(root);
|
||||
|
||||
// 前序遍历
|
||||
preOrder(root);
|
||||
|
||||
printf("\n输出所有值为 7 的节点\r\n");
|
||||
printVector(res, printFunc);
|
||||
delVector(res);
|
||||
}
|
||||
printf("\n输出所有值为 7 的节点\n");
|
||||
int vals[resSize];
|
||||
for (int i = 0; i < resSize; i++) {
|
||||
vals[i] = res[i]->val;
|
||||
}
|
||||
printArray(vals, resSize);
|
||||
|
||||
// 释放内存
|
||||
freeMemoryTree(root);
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user