Skip to content

Commit da4cae3

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <[email protected]>
1 parent 04c30ef commit da4cae3

File tree

2 files changed

+47
-3
lines changed

2 files changed

+47
-3
lines changed

0129_sum_root_to_leaf_numbers/sum_tree.c

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#include <stdio.h>
22
#include <stdlib.h>
33

4+
45
struct TreeNode {
56
int val;
67
struct TreeNode *left;
@@ -9,12 +10,13 @@ struct TreeNode {
910

1011
static int dfs(struct TreeNode* node, int sum)
1112
{
12-
int total = 0;
13+
/* Here we have to use pre-order */
14+
/* sum must be in argument stack of recusion.*/
1315
sum = sum * 10 + node->val;
14-
1516
if (node->left == NULL && node->right == NULL) {
1617
return sum;
1718
} else {
19+
int total = 0;
1820
if (node->left != NULL) {
1921
total += dfs(node->left, sum);
2022
}
@@ -25,7 +27,7 @@ static int dfs(struct TreeNode* node, int sum)
2527
}
2628
}
2729

28-
static int sumNumbers(struct TreeNode* root)
30+
int sumNumbers(struct TreeNode* root)
2931
{
3032
if (root == NULL) {
3133
return 0;
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* struct TreeNode {
8+
* int val;
9+
* TreeNode *left;
10+
* TreeNode *right;
11+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
12+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
13+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
14+
* };
15+
*/
16+
class Solution {
17+
public:
18+
int sumNumbers(TreeNode* root) {
19+
if (root == nullptr) {
20+
return 0;
21+
}
22+
return dfs(root, 0);
23+
}
24+
private:
25+
int dfs(TreeNode *root, int sum) {
26+
// Here we have to use pre-order.
27+
// sum must be in argument stack of recusion.
28+
sum = sum * 10 + root->val;
29+
if (root->left == nullptr && root->right == nullptr) {
30+
return sum;
31+
} else {
32+
int total = 0;
33+
if (root->left != nullptr) {
34+
total += dfs(root->left, sum);
35+
}
36+
if (root->right != nullptr) {
37+
total += dfs(root->right, sum);
38+
}
39+
return total;
40+
}
41+
}
42+
};

0 commit comments

Comments
 (0)