|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdbool.h> |
| 3 | +#include <stdlib.h> |
| 4 | + |
| 5 | +struct TreeNode { |
| 6 | + int val; |
| 7 | + struct TreeNode *left; |
| 8 | + struct TreeNode *right; |
| 9 | +}; |
| 10 | +bool hasPathSum(struct TreeNode *root, int sum) { |
| 11 | + if (root == NULL) |
| 12 | + return false; |
| 13 | + if (root->left == NULL && root->right == NULL) |
| 14 | + return root->val == sum; |
| 15 | + if (!root->left || !hasPathSum(root->left, sum - root->val)) { |
| 16 | + return hasPathSum(root->right, sum - root->val); |
| 17 | + } |
| 18 | + return true; |
| 19 | +} |
| 20 | + |
| 21 | +struct TreeNode *mk_node(int val) |
| 22 | +{ |
| 23 | + struct TreeNode *p = malloc(sizeof(*p)); |
| 24 | + p->val = val; |
| 25 | + p->left = p->right = NULL; |
| 26 | + return p; |
| 27 | +} |
| 28 | +void mk_child(struct TreeNode *root, struct TreeNode *left, struct TreeNode *right) |
| 29 | +{ |
| 30 | + root->left = left; |
| 31 | + root->right = right; |
| 32 | +} |
| 33 | +int main(int argc, char **argv) |
| 34 | +{ |
| 35 | + struct TreeNode *root = mk_node(5); |
| 36 | + mk_child(root, mk_node(4), mk_node(8)); |
| 37 | + struct TreeNode *left = root->left; |
| 38 | + struct TreeNode *right = root->right; |
| 39 | + mk_child(left, mk_node(11), NULL); |
| 40 | + mk_child(left->left, mk_node(7), mk_node(2)); |
| 41 | + mk_child(right, mk_node(13), mk_node(4)); |
| 42 | + mk_child(right->right, NULL, mk_node(1)); |
| 43 | + printf("%d\n", hasPathSum(root, 22)); |
| 44 | + printf("%d\n", hasPathSum(root, 26)); |
| 45 | + printf("%d\n", hasPathSum(root, 18)); |
| 46 | + printf("%d\n", hasPathSum(root, 27)); |
| 47 | + printf("%d\n", hasPathSum(root, 37)); |
| 48 | + printf("%d\n", hasPathSum(root, 100)); |
| 49 | + printf("%d\n", hasPathSum(root, 0)); |
| 50 | + return 0; |
| 51 | +} |
0 commit comments