|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +struct DynArray { |
| 4 | + int* mem; |
| 5 | + int size; |
| 6 | + int capacity; |
| 7 | +}; |
| 8 | + |
| 9 | +struct DynArray* createDynArray(int); |
| 10 | +void pushDynArray(struct DynArray*, int); |
| 11 | +void preorder_recurse(struct DynArray*, struct Node*); |
| 12 | + |
| 13 | +int* preorder(struct Node* root, int* returnSize) { |
| 14 | + struct DynArray* return_array = createDynArray(8); |
| 15 | + preorder_recurse(return_array, root); |
| 16 | + int* mem = return_array->mem; |
| 17 | + *returnSize = return_array->size; |
| 18 | + // Free the dynamic array structure after extracting the required info |
| 19 | + free((void*) return_array); |
| 20 | + return mem; |
| 21 | +} |
| 22 | + |
| 23 | +void preorder_recurse(struct DynArray* ret_arr, struct Node* tree) { |
| 24 | + if (!tree) { |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + // Root |
| 29 | + pushDynArray(ret_arr, tree->val); |
| 30 | + // Others from left to right |
| 31 | + for (int i = 0; i < tree->numChildren; ++i) { |
| 32 | + preorder_recurse(ret_arr, *(tree->children + i)); |
| 33 | + } |
| 34 | + |
| 35 | +} |
| 36 | + |
| 37 | +struct DynArray* createDynArray(int start_size) { |
| 38 | + struct DynArray* arr = malloc(sizeof(struct DynArray)); |
| 39 | + int* arr_mem = malloc(start_size * sizeof(int)); |
| 40 | + |
| 41 | + arr->mem = arr_mem; |
| 42 | + arr->capacity = start_size; |
| 43 | + arr->size = 0; |
| 44 | + |
| 45 | + return arr; |
| 46 | +} |
| 47 | + |
| 48 | +void pushDynArray(struct DynArray* arr, int val) { |
| 49 | + if (arr->size == arr->capacity) { |
| 50 | + int* mem = (int*) realloc((void*) arr->mem, 2 * arr->capacity * sizeof(int)); |
| 51 | + arr->mem = mem; |
| 52 | + arr->capacity *= 2; |
| 53 | + } |
| 54 | + *(arr->mem + arr->size) = val; |
| 55 | + ++(arr->size); |
| 56 | + return; |
| 57 | + |
| 58 | +} |
0 commit comments