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