Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit aaef872

Browse files
AC 530
1 parent 3e4e549 commit aaef872

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /