Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit a184333

Browse files
Sum root to leaf numbers
Signed-off-by: Leo Ma <begeekmyfriend@gmail.com>
1 parent c923ab2 commit a184333

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

129_sum_root_to_leaf_numbers/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test sum_tree.c
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
struct TreeNode {
5+
int val;
6+
struct TreeNode *left;
7+
struct TreeNode *right;
8+
};
9+
10+
static void recursive(struct TreeNode* node, int sum, int *total)
11+
{
12+
sum = sum * 10 + node->val;
13+
14+
if (node->left == NULL && node->right == NULL) {
15+
*total += sum;
16+
}
17+
18+
if (node->left != NULL) {
19+
recursive(node->left, sum, total);
20+
}
21+
22+
if (node->right != NULL) {
23+
recursive(node->right, sum, total);
24+
}
25+
}
26+
27+
static int sumNumbers(struct TreeNode* root)
28+
{
29+
if (root == NULL) {
30+
return 0;
31+
}
32+
33+
int total = 0;
34+
recursive(root, 0, &total);
35+
return total;
36+
}
37+
38+
int main(void)
39+
{
40+
struct TreeNode root, n10, n11, n20, n21, n22, n23;
41+
root.val = 1;
42+
n10.val = 2;
43+
n11.val = 2;
44+
n20.val = 3;
45+
n21.val = 4;
46+
n22.val = 4;
47+
n23.val = 3;
48+
root.left = &n10;
49+
root.right = &n11;
50+
n10.left = &n20;
51+
n10.right = &n21;
52+
n11.left = &n22;
53+
n11.right = &n23;
54+
n20.left = NULL;
55+
n20.right = NULL;
56+
n21.left = NULL;
57+
n21.right = NULL;
58+
n22.left = NULL;
59+
n22.right = NULL;
60+
n23.left = NULL;
61+
n23.right = NULL;
62+
printf("%d\n", sumNumbers(&root));
63+
return 0;
64+
}

0 commit comments

Comments
 (0)