forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path129.cpp
More file actions
30 lines (29 loc) · 711 Bytes
/
129.cpp
File metadata and controls
30 lines (29 loc) · 711 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//Sum root to leaf numbers
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int dfs(int parent, TreeNode* root){
int cur = parent*10+root->val;
int sum = 0;
if(root->left == NULL && root->right == NULL)
return cur;
if(root->left!=NULL)
sum = dfs(cur,root->left);
if(root->right!=NULL)
sum+=dfs(cur,root->right);
return sum;
}
int sumNumbers(TreeNode* root) {
if(root == NULL)
return 0;
return dfs(0,root);
}
};