Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitda4cae3

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent04c30ef commitda4cae3

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‎

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

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

1011
staticintdfs(structTreeNode*node,intsum)
1112
{
12-
inttotal=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
returnsum;
1718
}else {
19+
inttotal=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-
staticintsumNumbers(structTreeNode*root)
30+
intsumNumbers(structTreeNode*root)
2931
{
3032
if (root==NULL) {
3133
return0;
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include<bits/stdc++.h>
2+
3+
usingnamespacestd;
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+
classSolution {
17+
public:
18+
intsumNumbers(TreeNode* root) {
19+
if (root ==nullptr) {
20+
return0;
21+
}
22+
returndfs(root,0);
23+
}
24+
private:
25+
intdfs(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)

[8]ページ先頭

©2009-2025 Movatter.jp