|
| 1 | +/* |
| 2 | + * Copyright (C) 2022, Saul Lawliet <october dot sunbathe at gmail dot com> |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * 有序数组 转成 二叉搜索树? 用递归 |
| 6 | + */ |
| 7 | + |
| 8 | +#include <stdlib.h> /* malloc() */ |
| 9 | +#include "c/data-structures/array.h" |
| 10 | +#include "c/data-structures/binary-tree.h" |
| 11 | +#include "c/test.h" |
| 12 | + |
| 13 | +struct TreeNode *toBST(int *nums, int p, int q) { |
| 14 | + if (p >= q) return NULL; |
| 15 | + |
| 16 | + int mid = (p + q) / 2; |
| 17 | + struct TreeNode *node = malloc(sizeof(struct TreeNode)); |
| 18 | + node->val = nums[mid]; |
| 19 | + node->left = toBST(nums, p, mid); |
| 20 | + node->right = toBST(nums, mid+1, q); |
| 21 | + return node; |
| 22 | +} |
| 23 | + |
| 24 | +struct TreeNode *sortedArrayToBST(int *nums, int numsSize) { |
| 25 | + return toBST(nums, 0, numsSize); |
| 26 | +} |
| 27 | + |
| 28 | +void test(const char *expect, const char *nums) { |
| 29 | + arrayEntry *e = arrayParse1D(nums, ARRAY_INT); |
| 30 | + struct TreeNode *t = sortedArrayToBST(arrayValue(e), arraySize(e)); |
| 31 | + |
| 32 | + EXPECT_EQ_STRING_AND_FREE_ACTUAL(expect, treeToString(t)); |
| 33 | + |
| 34 | + arrayFree(e); |
| 35 | + treeFree(t); |
| 36 | +} |
| 37 | + |
| 38 | +int main(void) { |
| 39 | + test("[0,-3,9,-10,null,5]", "[-10,-3,0,5,9]"); |
| 40 | + test("[3,1]", "[1,3]"); |
| 41 | + |
| 42 | + return testOutput(); |
| 43 | +} |
0 commit comments