Skip to content

Commit 84fb47e

Browse files
committed
Added solution to leetcode#129
1 parent b346fce commit 84fb47e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

leetcode/cpp/Tree/129.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
//Sum root to leaf numbers
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* struct TreeNode {
6+
* int val;
7+
* TreeNode *left;
8+
* TreeNode *right;
9+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
int dfs(int parent, TreeNode* root){
15+
int cur = parent*10+root->val;
16+
int sum = 0;
17+
if(root->left == NULL && root->right == NULL)
18+
return cur;
19+
if(root->left!=NULL)
20+
sum = dfs(cur,root->left);
21+
if(root->right!=NULL)
22+
sum+=dfs(cur,root->right);
23+
return sum;
24+
}
25+
int sumNumbers(TreeNode* root) {
26+
if(root == NULL)
27+
return 0;
28+
return dfs(0,root);
29+
}
30+
};

0 commit comments

Comments
 (0)