forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
112.c
53 lines (45 loc) · 1.26 KB
/
112.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
bool hasPathSum(struct TreeNode *root, int sum) {
if (root == NULL) {
return false;
}
int remain = sum - root->val;
if (root->left == NULL && root->right == NULL && remain == 0) { /* leaf */
return true;
}
if (hasPathSum(root->left, remain) || hasPathSum(root->right, remain)) {
return true;
}
else return false;
}
void printTreePreOrder(struct TreeNode *p) {
if (p != NULL) {
printf("%d", p->val);
printTreePreOrder(p->left);
printTreePreOrder(p->right);
}
else printf("#");
}
int main() {
struct TreeNode *t = (struct TreeNode *)calloc(4, sizeof(struct TreeNode));
struct TreeNode *p = t;
p->val = 1;
p->left = ++t;
t->val = -2;
t->left = t->right = NULL;
p->right = ++t;
t->val = 0;
t->left = t->right = NULL;
printTreePreOrder(p); printf("\n");
printf("%d\n", hasPathSum(p, 1)); /* should be true */
printf("%d\n", hasPathSum(p, 0)); /* should be false */
printf("%d\n", hasPathSum(p, -1)); /* should be true */
return 0;
}