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 65b926b

Browse files
AC 112
1 parent 84d6341 commit 65b926b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎c/100-199/112-path-sum.c

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Copyright (C) 2022, Saul Lawliet <october dot sunbathe at gmail dot com>
3+
* All rights reserved.
4+
*
5+
* 递归思想即可, 注意只要叶子才算数
6+
*/
7+
8+
#include <stdbool.h>
9+
#include "c/data-structures/binary-tree.h"
10+
#include "c/test.h"
11+
12+
bool hasPathSum(struct TreeNode *root, int targetSum) {
13+
if (root == NULL) {
14+
return false;
15+
}
16+
17+
if (!root->left && !root->right) {
18+
return targetSum == root->val;
19+
}
20+
21+
return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);
22+
}
23+
24+
void test(bool expect, const char *rootStr, int targetSum) {
25+
struct TreeNode *root = treeParse(rootStr);
26+
27+
EXPECT_EQ_INT(expect, hasPathSum(root, targetSum));
28+
29+
treeFree(root);
30+
}
31+
32+
int main(void) {
33+
test(true, "[5,4,8,11,null,13,4,7,2,null,null,null,1]", 22);
34+
test(false, "[1,2,3]", 5);
35+
test(false, "[]", 0);
36+
37+
test(false, "[1,2]", 1);
38+
39+
return testOutput();
40+
}

0 commit comments

Comments
(0)

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