Skip to content

Commit 387769f

Browse files
committed
Create Sum Root to Leaf Numbers.cpp
1 parent a57563e commit 387769f

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Sum Root to Leaf Numbers.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for binary tree
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
int ans;
13+
void dfs(TreeNode *r,int val)
14+
{
15+
if (!r)return;
16+
if (!r->left&&!r->right)
17+
{
18+
ans+=val;
19+
return;
20+
}
21+
if (r->left)dfs(r->left,val*10+r->left->val);
22+
if (r->right)dfs(r->right,val*10+r->right->val);
23+
}
24+
int sumNumbers(TreeNode *root) {
25+
// Start typing your C/C++ solution below
26+
// DO NOT write int main() function
27+
if (!root)return 0;
28+
ans=0;
29+
dfs(root,root->val);
30+
return ans;
31+
}
32+
};

0 commit comments

Comments
 (0)