|
| 1 | +/* |
| 2 | + * Copyright (C) 2023, Saul Lawliet <october dot sunbathe at gmail dot com> |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * 前序遍历二叉树, 计算最小差值即可 |
| 6 | + */ |
| 7 | + |
| 8 | +#include "c/data-structures/binary-tree.h" |
| 9 | +#include "c/test.h" |
| 10 | + |
| 11 | +void walk(struct TreeNode *root, int *lastVal, int *min) { |
| 12 | + if (root->left) walk(root->left, lastVal, min); |
| 13 | + if (*lastVal >= 0) { |
| 14 | + int minus = root->val - *lastVal; |
| 15 | + if (*min > minus) { |
| 16 | + *min = minus; |
| 17 | + } |
| 18 | + } |
| 19 | + *lastVal = root->val; |
| 20 | + if (root->right) walk(root->right, lastVal, min); |
| 21 | +} |
| 22 | + |
| 23 | +int getMinimumDifference(struct TreeNode *root) { |
| 24 | + // 0 <= Node.val <= 10^5 |
| 25 | + int lastVal = -1; |
| 26 | + int min = 100000 + 1; |
| 27 | + |
| 28 | + walk(root, &lastVal, &min); |
| 29 | + |
| 30 | + return min; |
| 31 | +} |
| 32 | + |
| 33 | +void test(int expect, char *str) { |
| 34 | + struct TreeNode *root = treeParse(str); |
| 35 | + EXPECT_EQ_INT(expect, getMinimumDifference(root)); |
| 36 | + treeFree(root); |
| 37 | +} |
| 38 | + |
| 39 | +int main(void) { |
| 40 | + test(1, "[4,2,6,1,3]"); |
| 41 | + test(1, "[1,0,48,null,null,12,49]"); |
| 42 | + |
| 43 | + return testOutput(); |
| 44 | +} |
0 commit comments